時(shí)間:2023-05-30 16:57:01 | 來源:網(wǎng)站運(yùn)營
時(shí)間:2023-05-30 16:57:01 來源:網(wǎng)站運(yùn)營
云開發(fā) For Web:一站式開發(fā)下一代 Serverless Web 應(yīng)用:近兩年來,Serverless 無疑是前端圈里最火熱的話題之一,在各種技術(shù)峰會、各種技術(shù)文章里都能看到它的身影。如果你是一名前端開發(fā)者,一定很奇怪:/getUser?id=123
),如果使用 Serverless 服務(wù)的話,有多快呢?module.exports = async function(events, context) { const { id } = events.query.id const userInfo = await fetchUserInfo(id) // 調(diào)用后端微服務(wù),拉取用戶信息 return userInfo}
然后發(fā)布這個(gè)云函數(shù)(假設(shè)命名為 getUser
),并且為它設(shè)置一條路由:cloudbase service:create -f getUser -p /getUser
然后你就可以通過 https://xxx.com/getUser
來拉取數(shù)據(jù)了,同時(shí)還附贈海量彈性伸縮、異地多活、日志監(jiān)控等多方位的能力。// 使用 Web 端 SDKconst cloudbase = require('tcb-js-sdk')const app = cloudbase.init({ /* 初始化... */ })const db = app.database()// 插入文檔await db.collection('messages').add({ author: 'stark', message: 'Hello World!'})// 查詢文檔const data = await db.collection('messages').where({ author: 'stark'}).get()// 更新文檔await db.collection('messages').where({ author: 'stark'}).update({ message: 'Hi, Cloudbase!'})// 刪除文檔await db.collection('messages').where({ author: 'stark'}).remove()
const $ = db.command.aggregateconst result = await db .collection('message') .aggregate() .group({ // 以 author 字段作為 key,統(tǒng)計(jì)相同 author 的數(shù)量 _id: '$author' messagesCount: $.sum(1) }) .end() //=> { "_id": "stark", messagesCount: 12 }
更多的聚合搜索功能,可以參考:Aggregate | 云開發(fā) Cloudbase// 啟動事務(wù)const transaction = await db.startTransaction()// 在事務(wù)內(nèi)讀const data = await transaction.collection('messages') .doc({ /* <docId> */}) .get()// 在事務(wù)內(nèi)寫await transaction.collection('messages') .doc({ /* <docId> */}) .update({ /* <data> */})// 提交事務(wù)await transaction.commit()
watch()
方法就是為此設(shè)計(jì)的,每當(dāng)數(shù)據(jù)庫符合條件的文檔發(fā)生變化時(shí),都會觸發(fā) onChange
回調(diào),示例代碼如下:await db.collection('messages') .where({/* <query> */}) .watch({ onChange: snapshot => { console.log("收到snapshot!", snapshot) }, onError: error => { console.log("收到error!", error) } })
更多信息可以參考:數(shù)據(jù)庫實(shí)時(shí)推送 | 云開發(fā) Cloudbase// sum.jsmodule.exports = async function(events) { return events.a + events.b}
這一小段代碼很簡單,但是隱藏在它之下的卻是一整套龐大的 FaaS(函數(shù)即服務(wù))基礎(chǔ)設(shè)施,提供了諸如彈性伸縮、日志、監(jiān)控告警等多方面的能力。const cloudbase = require("tcb-js-sdk");const app = cloudbase.init({/* 初始化 */});app.callFunction({ // 云函數(shù)名稱 name: "sum", // 傳給云函數(shù)的參數(shù) data: { a: 1, b: 2 } }) .then(res => { console.log(res); // 輸出 "3" }) .catch(error);
// hello.jsmodule.exports = function() { return 'Hello, World!'}
然后我們直接通過命令行發(fā)布這個(gè)函數(shù),并為它創(chuàng)建一條路由:$ cloudbase functions:deploy hello$ cloudbase service:create -f hello -p /hello
隨后便可以通過 url 直接訪問這個(gè)云函數(shù):$ curl https://xxx.service.tcloudbase.com/helloHello, World!
具體可以參考:const cloudbase = require('@cloudbase/node-sdk')// 無需使用服務(wù)端秘鑰const app = cloudbase.init()const data = await app.database().where().get()
更詳細(xì)的內(nèi)容可以參考:uploadFile
,就可以一步完成上面的三件事情:const tcb = require("tcb-js-sdk");const app = tcb.init({ env: 'your-env-id'})const { fileID } = await app.uploadFile({ // 云端路徑 cloudPath: "/a/b/c/filename", // 需要上傳的文件,F(xiàn)ile 類型 filePath: document.getElementById('file').files[0]})
uploadFile
會返回一個(gè) fileID
,是云開發(fā)內(nèi)文件的唯一標(biāo)識符,我們可以使用 getTempFileURL
來獲取文件 URL 訪問鏈接:const tcb = require("tcb-js-sdk");const app = tcb.init({ env: 'your-env-id'})const { fileList } = app.getTempFileURL({ fileList: [ 'cloud://a/b/c' ]})// fileList 是一個(gè)有如下結(jié)構(gòu)的對象數(shù)組// [{// fileID: 'cloud://a/b/c', // 文件 ID// tempFileURL: 'http://xxx/xxx/xxx', // 臨時(shí)文件網(wǎng)絡(luò)鏈接// maxAge: 120 * 60 * 1000, // 有效期// }]
更詳細(xì)的內(nèi)容,可以參考:wx.cloud
中)create-react-app
快速生成的腳手架項(xiàng)目,所以大部分構(gòu)建和工程化的細(xì)節(jié)這里就略過不談了,我們直接來看代碼實(shí)現(xiàn),大致上實(shí)現(xiàn)了三個(gè)功能,括號中是使用的云開發(fā)能力:async function init() { // 使用匿名登錄 await auth.anonymousAuthProvider().signIn(); // 使用 refreshToken 的前 6 位作為 uid setUid(auth.hasLoginState().credential.refreshToken.slice(0, 6)); // 建立實(shí)時(shí)數(shù)據(jù)推送連接 await db .collection("messages") .where({}) .watch({ onChange(snapshot) { setList(snapshot.docs); setLoading(false); }, onError(err) { console.log(err); }, });}
建立實(shí)時(shí)連接之后,集合中的任何變化,都會觸發(fā) onChange()
回調(diào),然后我們使用 setList()
來更新界面上的消息數(shù)據(jù)。sendMessage()
方法,直接使用 add()
方法向數(shù)據(jù)庫寫入數(shù)據(jù)就可以了:// 發(fā)送消息async function sendMessage() { const message = { timestamp: new Date().getTime(), text, uid, }; await db.collection("test").add(message); // 清空輸入欄 setText("");}
當(dāng)然以上只是局部的代碼片段,整體代碼可以參考:$ npm run build
構(gòu)建產(chǎn)物會生成到 build
目錄下。$ cloudbase hosting:deploy ./build -e your-env-id
發(fā)布完成后,你便可以通過 https://xxxx.tcb.qcloud.la/xxxx
的來訪問你的應(yīng)用了。進(jìn)一步,你還可以為它綁定自定義域名。關(guān)鍵詞:
客戶&案例
營銷資訊
關(guān)于我們
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。