Building a Backend Function
Creating a Backend Function
- Log in to the FunctionGraph console, and choose Functions > Function List in the navigation pane.
- Click Create Function.
- Set the function information, as shown in Figure 1.
- For Template, select Create from scratch.
- For Function Name, enter AIDemo.
- For App, select default.
- For Agency, select serverless_trust.
The selected agency must have permissions to access API Gateway, Image Moderation, and OBS resources. For details on how to create an agency, see Creating an Agency.
- For Runtime, select Node.js 6.10.
- For Handler, enter index.handler.
- For Code Entry Mode, select Edit code inline.
- Enter the following code in the code box:
const https = require('https'); const fs = require('fs'); const ObsClient = require('esdk-obs-nodejs'); //References an OBS SDK. let PAYLOAD = {}; let CONTEXT = null; const PATH = '/tmp/image.png' exports.handler = function (event, context, callback) { CONTEXT = context; //Cross-origin verification if (event.httpMethod === "OPTIONS") { console.log('OPTIONS request, pass.'); const result = { body: '', headers: { "Content-Type":"application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type,Accept", "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE" }, statusCode: 200, isBase64Encoded: false }; callback(null, result); return; } new Promise(function(resolve, reject) { var token = context.getToken(); const options = { hostname: 'moderation.cn-north-1.myhuaweicloud.com', port: 443, path: '/v1.0/moderation/image', method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf8', 'X-Auth-Token': token } }; PAYLOAD = constructPayload(event); console.log("Sending request to AIS...") const req = https.request(options, (res) => { var status = res.statusCode console.log("status:", status) res.on('data', (d) => { resolve(d.toString()); }); }); req.on('error', (e) => { console.error(e); }); req.write(JSON.stringify(PAYLOAD)); req.end(); }).then(function(value) { // check image and save if porn const resultObj = JSON.parse(value); const bucket = context.getUserData('BUCKET'); const apigBody = { result: resultObj.result.detail.porn, suggestion: resultObj.result.suggestion, eiInfo: resultObj.result, }; saveImage(PAYLOAD.image, resultObj.suggestion || '', bucket).then((err) => { // return apig result const result = { body: JSON.stringify(apigBody), headers: { "Content-Type":"application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type,Accept", "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE" }, statusCode: 200, isBase64Encoded: false }; callback(null, result); }); }); } function constructPayload(event) { if (event.httpMethod != "POST") { return { "image": "", "url": "https://bjbucket.obs.myhuaweicloud.com/70923411.jpg",//Example URL. Replace it with the actual URL. "categories": [ "porn" ], "threshold" : "" } } const bodyStr = new Buffer(event.body, 'base64').toString('ascii'); const body = JSON.parse(bodyStr); if (body.url != null && body.url.trim() != "") { return { "image": "", "url": body.url, "categories": [ "porn" ], "threshold" : "" } } else { return { "image": body.image, "url": "", "categories": [ "porn" ], "threshold" : "" }; } } function saveImage(image, imageInfo, bucket) { return new Promise((resolve, reject) => { if (/*imageInfo !== 'pass'*/false) { console.log('>>>>>>>not pass, start save image'); writeImage(image).then((err) => { if (!err) { uploadImage(PATH, bucket).then((err) => { resolve(err); }); } else { resolve(err) } }); } else { resolve(null); } }); } function writeImage(image) { return new Promise((resolve, reject) => { const imageBuffer = new Buffer(image, 'base64'); fs.writeFile(PATH, imageBuffer, function(err) { console.log('>>>>>>>>>>write file:', err); resolve(err); }); }); } function uploadImage(path, bucket) { return new Promise((resolve, reject) => { // upload path to bucket; const client = buildOBSClient(CONTEXT); client.putObject({ Bucket: bucket, Key: `image-${(new Date()).valueOf()}.png`, SourceFile: path }, (err, result) => { if (err) { console.error('Upload Error-->' + err); } else { console.log('Upload Status-->' + result.CommonMsg.Status + '. uploading file OK!'); } resolve(err); }); }); } function buildOBSClient(context) { // Obtains a temporary AK and SK to access OBS. An agency is required to access IAM. const my_access_key = context.getAccessKey(); const my_secret_access_key = context.getSecretKey(); console.log('begin create obs client!'); return new ObsClient({ access_key_id: my_access_key, secret_access_key: my_secret_access_key, server: 'obs.cn-north-1.myhuaweicloud.com'//Example. Replace it with the actual value. }); }
- In the right pane of the page, review the function configuration and billing information, and click Create Function.
Creating an APIG Trigger for the Backend Function
- Log in to the FunctionGraph console, choose Functions, and click AIDemo to go to the function details page.
- Click the Triggers tab and click Create Trigger, as shown in Figure 2.
- Select APIG for Trigger Type, and set the trigger information, as shown in Figure 3.
- For API Name, enter API_AIDemo.
- For API Group, select function. For details on how to create an API group, see Creating an API group.
- For Environment, select RELEASE.
- For Security Authentication, select None.
- For Protocol, select HTTPS.
- For Timeout (ms), enter 5000.
After you create an APIG trigger for the RELEASE environment, an API is generated and published on the API Gateway console. The API can be directly called by the function.
- Click OK.
The invocation address of the APIG trigger for the backend function is https://d237af6bc4214cc383b5f2b40a3af234.apigw.cn-north-1.huaweicloud.com/AIDemo. You will use this address when building a frontend function.
Last Article: Preparation
Next Article: Building a Frontend Function



Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.