Initialize the framework
You must initialize the mPaaS framework before you can use Remote Procedure Call (RPC).
export default class EntryAbilityStage extends AbilityStage {
async onCreate() {
const app = this.context;
MPFramework.create(app);
const instance: MPFramework = MPFramework.instance;
const ctx: Context = instance.context
}
}
Generate RPC code
The console automatically generates the following code. If you have not upgraded the console, you can manually create the model in the specified format, such as `VipInfo.ts`.
interface VipInfo{
expireTime:number,
level:number
}A model can contain another model, such as `userInfo.ts`.
interface UserInfo{
vip:VipInfo,
name:string,
age:number
}The console automatically generates the wrapper parameter, such as `LoginPostReq.ts`.
interface LoginPostReq{
_mPaaSCustomBody:UserInfo
}The interface is automatically generated. If you have not upgraded the console, you can manually configure the interface. The following code shows an example that uses `Client.ets`.
import {MPRpc} from '@mpaas/rpc'
class Client{// The type in <> is the return value type. needsign and ispb are required fields.
async loginPost(req:LoginPostReq):Promise<string>{// The return type is string.
return MPRpc.executeRpc<string>(this,{
operationType:"com.antcloud.request.post",
needSign:false,
isPb:false
},req);
}
}Call RPC interfaces
Call RPC requests in a subthread. You can use the subthread calling interface that is encapsulated in the `MPRpcInterface` middle layer. By default, the callback method runs on the main thread. The following code shows an example.
// Prerequisite: Initialize RPC.
MPRpc.init();
function testRpc(){
let cl = new Client();
let account:VipInfo = {
expireTime:1,
level:1
};
let user:UserInfo = {
vip:account,
name:"handsome",
age:14
}
let req:LoginPostReq ={
_mPaaSCustomBody:user
}
cl.loginPost(req).then((result)=>{
console.log("result")
}).catch((e:Error)=>{
console.log(e.message)// Get the specific error cause from e.message.
});
}You can use `try catch` to catch exceptions. Exceptions are thrown when gateway errors occur. For more information, see Gateway result codes.
Custom request configurations
Set a timeout period
Add the `timeout` configuration. The following code shows an example.
import {MPRpc} from '@mpaas/rpc'
class Client{// The type in <> is the return value type. needsign and ispb are required fields.
async loginPost(req:UserInfo):Promise<string>{
return MPRpc.executeRpc<string>(this,{
operationType:"com.antcloud.request.post",
needSign:false,
isPb:false,
timeout:1000000// Set the timeout period. The default is 1 minute.
},req);
}
}Set a request URL
Add the URL configuration. The following code shows an example.
import {MPRpc} from '@mpaas/rpc'
class Client{// The type in <> is the return value type. needsign and ispb are required fields.
async loginPost(req:UserInfo):Promise<string>{
return MPRpc.executeRpc<string>(this,{
operationType:"com.antcloud.request.post",
needSign:false,
isPb:false,
url:"https://xxxx.xx/xx/"// Set the request URL. The default is the gateway address.
},req);
}
}Set a request header
Add the header configuration. The following code shows an example.
import {MPRpc} from '@mpaas/rpc'
// Initialize the header.
let headers:Map<string,string> = new Map();
headers.set("key1","value1");
headers.set("key2","value2");
class Client{// The type in <> is the return value type. needsign and ispb are required fields.
async loginPost(req:UserInfo):Promise<string>{
return MPRpc.executeRpc<string>(this,{
operationType:"com.antcloud.request.post",
needSign:false,
isPb:false,
header:headers // Set the headers.
},req);
}
}Custom RPC interceptors
Initialize the interceptor.
The `preHandle` method runs before a request is sent. It returns an `RpcInvokeContext` object that you can use to manage the header, URL, and timeout. If this method returns `false`, the request is intercepted and stopped. The RPC interface can then catch the exception.
The `postHandle` method runs after a request is complete. It returns an `RpcInvokeContext` object that you can use to retrieve the response header. If this method returns `false`, the request is intercepted and stopped. The RPC interface can then catch the exception.
The `handleException` method intercepts requests when exceptions occur.
import {RpcInterceptor,RpcInvokeContext} from "@mpaas/rpc"; class interceptor implements RpcInterceptor{ preHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } postHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } handleException(rpcInvokeContext: RpcInvokeContext, exception: RPCException) { throw exception; } }Configure the interceptor.
Intercept a specific RPC.
Add the `interceptor` configuration to the automatically generated code.
import {MPRpc} from '@mpaas/rpc' import {RpcInterceptor,RpcInvokeContext} from "@mpaas/rpc"; class interceptor implements RpcInterceptor{ preHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } postHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } handleException(rpcInvokeContext: RpcInvokeContext, exception: RPCException) { throw exception; } } class Client{// The type in <> is the return value type. needsign and ispb are required fields. async loginPost(req:UserInfo):Promise<string>{ return MPRpc.executeRpc<string>(this,{ operationType:"com.antcloud.request.post", needSign:false, isPb:false, interceptor:new interceptor() },req); } }Set a global interceptor.
In the
MPRpcinterface, set the following:import {RpcInterceptor,RpcInvokeContext} from "@mpaas/rpc"; import {MPRpc} from '@mpaas/rpc' class interceptor implements RpcInterceptor{ preHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } postHandle(rpcInvokeContext: RpcInvokeContext): boolean { return true; } handleException(rpcInvokeContext: RpcInvokeContext, exception: RPCException) { throw exception; } } MPRpc.addGlobalInterceptor(new interceptor());
Data encryption
Add the mpaasnetconfig.json file to the rawfile directory:
`type`: The encryption type. Valid values are ECC, RSA, and SM2.
`crypt`: Specifies whether to enable encryption.
`gw`: Specifies whether to use Ant Group's self-developed gzip. This parameter must be set to `true`.
`pubKey`: The public key. The public key must match the encryption type.
`gwList`: The URLs for which encryption is supported. Separate multiple URLs with commas (,). Only requests to matching URLs are encrypted.
{
"type": "ECC",// Supports ECC, RSA, and SM2.
"crypt": false,// Specifies whether to enable encryption.
"gw": true,// Use Ant Group's self-developed gzip.
"pubKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEx796auKwF42leWWX/cwvffrvz/M2\nd6f4ovv4G7wmu45Ed+5WBDfp7vKHB0P3il4SXmvK6be6m1MhL2kkY8Kj0Q==\n-----END PUBLIC KEY-----",
"gwList":"https://mgw.mpaas.cn-hangzhou.aliyuncs.com/mgw.htm,http://11.164.247.80/mgw.htm"
}Data signing
Configure the settings in the interface file. Set `needSign` to `true`. Set the signature type in `signType`. The supported types are MD5 (type 0), SHA256 (type 4), and SM3 (type 5).
import {MPRpc} from '@mpaas/rpc'
class Client{// The type in <> is the return value type. needsign and ispb are required fields.
async loginPost(req:UserInfo):Promise<string>{
return MPRpc.executeRpc<string>(this,{
operationType:"com.antcloud.request.post",
needSign:true, // The default is false.
isPb:false,
signType:0 // If you do not specify this parameter, the default value 0 (MD5) is used.
},req);
}
}Generate a security image
To enable signature verification, you must generate a security image. For more information, see Obtain the security image.