1 Basic Introduction
Uni-app is a cross-end development framework based on vue.js. A set of code can be published to different platforms such as APP, applets, Web, etc
The @CloudBase/JS-SDK provided by Tencent Cloud development platform Cloudbase enables developers to use JavaScript to access Cloudbase services and resources from Web terminals (such as PC Web pages and wechat public platform H5).
However, @Cloudbase/JS-SDK only supports Web (browser environment) development, not other web-like platforms (such as applets). These platforms differ significantly from the browser environment in features such as network requests, local storage, platform identity, and so on.
The @Cloudbase/JS-SDK does not recognize these differences. For example, @Cloudbase/Js-SDK does not know how these platforms send network requests, so we cannot use @Cloudbase/Js-SDK directly when developing Web like applications.
In view of these differences, @Cloudbase/JS-SDK provides a complete set of adaptation and extension solutions. The adaptors of corresponding platforms can be developed in accordance with the specifications of these solutions to achieve platform compatibility
As for Uni-App, unlike the browser, which extends unique UNI objects based on ECMAScript, it cannot use @Cloudbase/JS-SDK directly because of the differences in features such as network requests, local storage and so on
If you want uni-App applets and PC Web applications to use the same set of cloud development back-end services, you need to develop an adapter for Uni-App
2 the adapter
Before developing the adapter, install the interface declaration module @Cloudbase/Adapter-interface
# npm
npm i @cloudbase/adapter-interface
# yarn
yarn add @cloudbase/adapter-interface
Copy the code
The adapter module needs to export an Adapter object:
const adapter = {
genAdapter,
isMatch,
// Runtime marks platform uniqueness
runtime: 'Platform name'
};
export adapter;
export default adapter;
Copy the code
Must contain the following three fields:
runtime
:string
, the name of the platform, used to mark uniqueness of the platform;isMatch
:Function
To check whether the current operating environment is a platformboolean
Value;genAdapter
:Function
To createadapter
Entity.
runtime
The Runtime is used to mark platform uniqueness
isMatch
The isMatch function is used to determine whether the current runtime environment matches the adapter, usually by determining platform-specific global variables, apis, and so on.
We can determine uni-app by the UNI object
function isMatch() {
return uni ? true : false
}
Copy the code
genAdapter
The genAdapter function returns the entity object of the adapter, structured as follows:
interface SDKAdapterInterface {
// Global root variable, browser environment is window
root: any;
/ / the WebSocket class
wsClass: WebSocketContructor;
/ / request
reqClass: SDKRequestConstructor;
// Persistence =local degraded to None when there is no localstorage
localStorage? : StorageInterface;// No sessionStorage persistence= Session degraded to NonesessionStorage? : StorageInterface;// Preferred storage mode over persistenceprimaryStorage? : StorageType;// Get the platform unique application identifier APIgetAppSign? () :string;
}
Copy the code
We simply use the methods provided by UNI-app to implement the specified interface. Example:
// Request class is a platform-specific network Request, which must implement post/upload/ Download three public interfaces
export class UniRequest extends AbstractSDKRequest {
// Implement the POST interface
public post(options: IRequestOptions) {
const { url, data, headers } = options
return new Promise((resolve, reject) = > {
try {
uni.request({
url,
data,
header: headers,
method: 'POST'.success: (res) = > {
resolve(res)
},
fail: (err) = > {
reject(err)
}
})
} catch (error) {
reject(error)
}
});
}
// Implement the upload interface
public upload(options: IUploadRequestOptions) {
const { url, file, name } = options
return new Promise((resolve, reject) = > {
try {
uni.uploadFile({
url,
filePath: file,
name,
success: (res) = > {
resolve(res)
},
fail: (err) = > {
reject(err)
}
})
} catch (error) {
reject(error)
}
});
}
// Implement the Download interface
public download(options: IRequestOptions) {
const { url } = options
return new Promise((resolve, reject) = > {
try {
uni.downloadFile({
url,
success: (res) = > {
resolve(res)
},
fail: (err) = > {
reject(err)
}
})
} catch(error) { reject(error) } }); }}/ / Storage for platform-specific local Storage, must implement the setItem/the getItem/removeItem/clear four interfaces
export const Storage: StorageInterface = {
setItem(key: string, value: any) {
uni.setStorage({
key,
data: value,
success: (res) = > {
console.log(res);
}
})
},
getItem(key: string) :any {
return uni.getStorageSync(key)
},
removeItem(key: string) {
uni.removeStorage({
key,
success: (res) = > {
res
}
})
},
clear() {
uni.clearStorage()
}
};
// WebSocket is a platform-specific WebSocket, consistent with the HTML5 standard specification
export class WebSocket {
constructor(url: string, options: object = {}) {
const socketTask: WebSocketInterface = {
set onopen(cb) {
// ...
},
set onmessage(cb) {
// ...
},
set onclose(cb) {
// ...
},
set onerror(cb) {
// ...
},
send: (data) = > {
// ...
},
close: (code? :number, reason? :string) = > {
// ...
},
get readyState() {
// ...
return readyState;
},
CONNECTING: 0.OPEN: 1.CLOSING: 2.CLOSED: 3
};
returnsocketTask; }}The genAdapter function creates the Adapter entity
function genAdapter() {
const adapter: SDKAdapterInterface = {
// The root object is the global root object, if not, fill in the blank object {}
root: {},
reqClass: UniRequest,
wsClass: WebSocket as WebSocketContructor,
localStorage: Storage,
// Cache the storage policy first. It is recommended to always keep localstorage
primaryStorage: StorageType.local,
// sessionStorage is optional. If the platform does not support sessionStorage, this parameter is optional
sessionStorage: sessionStorage
};
return adapter;
}
Copy the code
WebSocket is not implemented here, but can be implemented on demand if necessary
3 Access Process
Now that we have the adapter, we can happily use Cloudbase in our UNI-app project
Step 1: Install and import the adapter
@ cloudbase/js – SDK installation
# @ cloudbase/js - SDK installation
npm i @cloudbase/js-sdk
Copy the code
Introduce the adapter in the business code (here I put the adapter in the utils directory)
import cloudbase from "@cloudbase/js-sdk";
import adapter from '@/utils/adapter.ts'
cloudbase.useAdapters(adapter);
Copy the code
Step 2: Configure the security application source
Log in to the CloudBase console and enter the mobile application security Source column on the security configuration page:
Click the “Add App” button and enter the app id, such as UniApp
A secure application is created, as shown in the following figure:
Step 3: Initialize cloud development
Pass the security application information configured in Step 2 as a parameter to the init method when initializing cloud development in business code:
import cloudbase from '@cloudbase/js-sdk';
import adapter from '@/utils/adapter.ts'
cloudbase.useAdapters(adapter);
cloudbase.init({
env: 'environmental ID'.appSign: 'Application identifier'.appSecret: {
appAccessKeyId: 'Application Credential Version number'
appAccessKey: 'Application credentials'}})Copy the code
- The environment ID can be obtained in the environment overview:
-
AppSign: String, application identifier, corresponding to the column of “Application Identifier” in the mobile application security source (such as UNIApp)
-
AppSecret: Object, application credential information, including the following fields:
appAccessKeyId
:string
Corresponding to the column of “Version” in the mobile application security source,A maximum of two versions of credential information can be added to the same application idIn order to distinguish between development and production environments;appAccessKey
:string
, corresponding to the information obtained after clicking “Obtain credentials” in the “Operation” column of mobile application security source.
Step 4: Write the business code
After all this preparation, you can write your own business code.
Let’s say we want to access the cloud function test:
const tcb = cloudbase.init({
env: 'environmental id'.appSign: 'uniapp'.appSecret: {
appAccessKeyId: '1'.appAccessKey:'Application credentials'
}
})
tcb.callFunction({
name: 'test'
}).then(res= > {
console.log(res)
})
Copy the code
4 Access permission problems
After the above preparations, we may still be unable to access cloud functions, cloud databases, cloud storage and other resources. The following information appears on the console:
This allows you to view access permissions, using cloud functions as an example:
4.1 Permission Control
Click the permission control button for the cloud function
Configure the cloud function access permissions, such as setting the test permission to true below
4.2 Login Authorization
To access applications without logging in, turn on the Not Logged in option in login authorization
Now, you can have fun visiting ~
5 Source Code address
Github.com/Melonvin/un…