background
Since 2000, xml
has become popular as a data exchange format, server splicing xml
interface, client js gets xml
content, and dynamically modify pages.
A few years later, the smaller amount of data json
replaced xml
.
After the arrival of the mobile Internet, the proliferation of interfaces has been exacerbated because of the division of clients.
In the blink of an eye, the interface has been playing for 20 years. Other technologies are developing rapidly, but the front-end and back-end interaction has always been an interface, and there is no innovation.
js already has import
, export
, why can't calling the back-end interface be the same as calling a front-end module?
serverless, let this all start to change.
Amazon lambda
proposed the concept of cloud functions, no longer using restful
url
, but still based on json
exchange front-end data 5e58df403.
uniCloud
also initially started with support for cloud functions, but we found that this was still not elegant, concise, intuitive, and unified.
Starting from HBuilderX 3.4
, uniCloud
launched the " cloud object ", which makes calling cloud services really as simple as calling front-end modules.
What is a cloud object
Cloud object: The server writes the API, the client calls the API, and no longer develops the interface for transmitting json. Clearer thinking and simpler code.
For example, the server writes a cloud object news, which exports several methods: add(), getList(), getDetailById(), softDel(), changeContent(), allowPublic(), addComment(), getComments(), etc. method.
The client-side js can directly import
this news
cloud object, and then directly call add
and other methods.
The server sample code is as follows:
Create a new cloud function/cloud object in the uniCloud/cloudfunctions directory in HBuilderX, select the type as cloud object, and name it news. Open the cloud object entry index.obj.js
and add an add method.
// 云对象名:news
module.exports = {
add(title, content) {
title = title.trim()
content = content.trim()
if(!title || !content) {
return {
errCode: 'INVALID_NEWS',
errMsg: '标题或内容不可为空'
}
}
// ...其他逻辑
return {
errCode: 0,
errMsg: '创建成功'
}
}
}
Then in the client's js, import
this news
object, call its add
method.
const news = uniCloud.importObject('news') //第一步导入云对象
async function add () {
try {
const res = await news.add('title demo', 'content demo') //导入云对象后就可以直接调用该对象的方法了,注意使用异步await
uni.showToast({
title: '创建成功'
})
} catch (e) { // 符合uniCloud响应体规范 https://uniapp.dcloud.net.cn/uniCloud/cf-functions?id=resformat,自动抛出此错误
}
}
You can see that the code of the cloud object is very clear, and the number of lines of code is only 27 lines.
For the same logic, using the traditional interface method requires more code, see below:
// 传统方式调用云函数-云函数代码
// 云函数名:news
// 云函数入口index.js内容如下
'use strict';
exports.main = async (event, context) => {
const {
method,
params
} = event
switch(method) {
case 'add': {
let {
title,
content
} = params
title = title.trim()
content = content.trim()
if(!title || !content) {
return {
errCode: 'INVALID_NEWS',
errMsg: 'NEWS标题或内容不可为空'
}
}
// ...省略其他逻辑
return {
errCode: 0,
errMsg: '创建成功'
}
}
}
return {
errCode: 'METHOD_NOT_FOUND',
errMsg: `Method[${method}] not found`
}
};
Traditional way to call cloud functions - client code
async function add () {
try {
const res = uniCloud.callFunction({
name: 'news',
data: {
method: 'add',
params: {
title: 'title demo',
content: 'content demo'
}
}
})
const {
errCode,
errMsg
} = res.result
if(errCode) {
uni.showModal({
title: '创建失败',
content: errMsg,
showCancel: false
})
return
}
uni.showToast({
title: '创建成功'
})
} catch (e) {
uni.showModal({
title: '创建失败',
content: e.message,
showCancel: false
})
}
}
The above traditional development requires 68 lines of code. Compared with the 27 lines of code for cloud objects, it can be said that it is "ugly and long"
More powerful features
1. Preprocessing and postprocessing
No matter which method of the cloud object is requested, it will go through the _before
method before starting, and will execute the _after
method at the end. This contributes to uniform early checksum and formatting errors.
Example:
// news/index.obj.js
module.exports = {
_before: function(){
this.startTime = Date.now() // 在before内记录开始时间并在this上挂载,以供后续流程使用
const methodName = this.getMethodName() // 获取当前请求的云对象方法名
if(methodName === 'add' && !this.getUniIdToken()) {
throw new Error('token不存在')
}
},
add: function(title = '', content = '') {
if(title === 'abc') {
throw new Error('abc不是一个合法的news标题')
}
return {
errCode: 0,
errMsg: '创建成功'
}
},
_after(error, result) {
if(error) {
throw error // 如果方法抛出错误,也直接抛出不处理
}
result.timeCost = Date.now() - this.startTime
return result
}
}
2. The return value of the cloud object is compatible with the uniCloud response body specification
The default return value of the cloud object is uniCloud响应体规范
, which is convenient for the client to intercept errors uniformly.
Whether the network is abnormal or the token expires, the prompt can be intercepted uniformly.
See uniCloud response body specification for details
3. Automatically display the interactive interface
Every time the code for the client to be connected to the network is written, the developer will inevitably write a bunch of code repeatedly: first call the loading waiting box, and then close the loading after the network is completed. If the server is abnormal, a prompt box will pop up.
The original writing (line 22):
uni.showLoading({
title: '联网中...'
})
uni.request({
url: "xxxx",
success: (res) => {
uni.showToast({
title: '添加成功',
icon: 'success',
mask: true,
duration: duration
});
},
fail: (err) => {
uni.showModal({
content: err.errMsg,
showCancel: false
});
},
complete: () => {
uni.hideLoading();
}
});
Now, when calling methods of cloud objects, the above functions are provided by default.
- The loading waiting box is displayed when the request for networking starts,
- Hide loading after finishing
- If the request reports an error, display a pop-up window (can also be configured to display Toast)
const news = uniCloud.importObject('news') //第一步导入云对象
try {
await news.add('title demo', 'content demo') //导入云对象后就可以直接调用该对象的方法了,注意使用异步await
uni.showToast({
title: '添加成功'
})
} catch (e) {}
As above, it used to take 23 lines of code, but now it can be done in 7 lines!
Of course, these UI strategies can be customized.
- URLization
For historical compatibility considerations, cloud objects also provide a URLization scheme. Developers can still convert a cloud object to a http
url
interface of ---a3edcbc1237ff8258cabc87c93db7929---.
Summarize
Many benefits of using cloud objects:
- clearer logic
- leaner code
- Fewer collaboration costs (and contradictions~)
- When the client calls, there is a complete code prompt in the IDE, and the method parameters can be prompted. (Transmission
json
can not be prompted inide
) - Automatically supports the uniCloud response body specification , which is convenient for error interception and unified processing
For more cloud object introduction, see: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj.html
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。