Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Cloud Function Utility Library


May 22, 2021 Mini Program Cloud Development Advanced



Cloud functions often need to deal with some very basic things, such as time, arrays, numbers, objects, strings, IP, etc. , the cost of making their own wheels is very high, this time we can go to the awesome nodejs Github to find some others have written open source modules, we directly download the introduction can be, the following list of better tools and will be combined with cloud functions to give some detailed cases.

First, moment time processing and Timezone world time

1, cloud function time processing

When developing small programs, you often need to format time, handle relative time, calendar time, and time multilingual issues, this time you can use the more popular momentjs, you can refer to the moment Chinese documentation

Use the developer tool to create a new cloud function, such as moment, and then add the dependency on the latest version of moment latest latest at package.json:

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "moment": "latest"
  4. }

The code in .js is changed as follows, we set the moment area to China, format the 十二月 23日 2019, 4:13:29 下午 style and how many minutes ago relative to the current 多少分钟前

  1. const cloud = require('wx-server-sdk')
  2. const moment = require("moment");
  3. cloud.init({
  4. env: cloud.DYNAMIC_CURRENT_ENV,
  5. })
  6. exports.main = async (event, context) => {
  7. moment.locale('zh-cn');
  8. time1 = moment().format('MMMM Do YYYY, h:mm:ss a');
  9. time2 = moment().startOf('hour').fromNow();
  10. return { time1,time2}
  11. }

It is worth noting that the time zone in the cloud function is UTC-0, not UTC-8, the formatted time and time in the country is 8 hours time difference, if the time format in the cloud function to convert the time format to string needs to give the number of hours 8 (this processing needs to pay attention to some details, will not be processed the proposed modification of the time zone), you can also modify the time zone.

2. Two ways for functions to handle time zones

The cloud function modifies the time zone so that we can use the timezone dependency (and moment is the same open source author), timezone technical documentation

Add the latest version of moment-timezone's latest latest dependency at package.json, and then modify the corresponding code above.

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "moment-timezone": "latest"
  4. }

You can then convert the time zone by using the following code in the cloud function.

  1. const moment = require('moment-timezone');
  2. time1 = moment().tz('Asia/Shanghai').format('MMMM Do YYYY, h:mm:ss a');

In addition to using moment to handle the time zone of a cloud function, you can add a field TZ with a value of Asia/Shanghai to specify the time zone by Asia/Shanghai the cloud function (in the cloud development console).

Second, access to public IP

Sometimes we want to be able to get the public IP of the server, such as the whitelist for the IP address, or want to query the address of the server according to the IP, ipify is a free and useful dependency, through which we can also get the public NETWORK IP, ipify Github address of the server where the cloud function is located.

Use the developer tool to create a new getip cloud function, then enter the following code and add the latest version of the ipify dependency to package.json's "dependencies":

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "ipify": "latest"
  4. }

The code in .js the following, calling ipify to return the server address of ipv4:

  1. const cloud = require('wx-server-sdk')
  2. const ipify = require('ipify');
  3. cloud.init({
  4. env: cloud.DYNAMIC_CURRENT_ENV,
  5. })
  6. exports.main = async (event, context) => {
  7. return await ipify({ useIPv6: false })
  8. }

Then right-click the getip cloud function root, select Open in the terminal, enter the npm install installation dependency, and then upload and deploy all files. W e can call this cloud function on the small terminal, we can get the public IP of the cloud function server, this IP is random and limited a few, repeatedly call getip, you can exhaust all the cloud function server ip. Maybe you'll need an IP whitelist when using cloud functions to connect databases or use cloud functions to build weChat public numbers in the background, and we can add these ips to the whitelist so that cloud functions can do a lot of things.

Third, decrypt Crypto

The crypto module is one of the core modules of nodejs and provides security-related features, including a complete package of hash, HMAC, encryption, decryption, signature, and authentication capabilities for OpenSSL. Since the crypto module is a built-in module, we introduced it without downloading it.

Using developer tools to create a new cloud function, such as crypto, and enter the following code in index.js, let's look at which crypto supports encryption algorithms and take MD5 encryption as an example:

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. const crypto = require('crypto');
  6. exports.main = async (event, context) => {
  7. const hashes = crypto.getHashes();
  8. //获取crypto支持的加密算法种类列表
  9. //md5 加密 CloudBase2020 返回十六进制
  10. var md5 = crypto.createHash('md5');
  11. var message = 'CloudBase2020';
  12. var digest = md5.update(message, 'utf8').digest('hex');
  13. return {
  14. "crypto支持的加密算法种类":hashes,
  15. "md5加密返回的十六进制":digest
  16. };
  17. }

After deploying the cloud function, we can see from the returned results that the cloud function crypto module supports 46 encryption algorithms.

Four, Lodash utility library

Lodash is a consistent, modular, high-performance JavaScript utility library that makes JavaScript easier by making it easier to use data types such as array, number, objects, string. Lodash's modular approach is ideal for: traversing arrays, objects, and strings;

Technical documentation: Lodash official documentation, Lodash Chinese documentation

Use the developer tool to create a new cloud function, such as lodash, and then add the dependency on the latest version of lodash latest at package.json:

  1. "dependencies": {
  2. "lodash": "latest"
  3. }

The code in .js in the index is modified as follows, and here the chunk method of lodash is used to split the array:

  1. const cloud = require('wx-server-sdk')
  2. var _ = require('lodash');
  3. cloud.init({
  4. env: cloud.DYNAMIC_CURRENT_ENV,
  5. })
  6. exports.main = async (event, context) => {
  7. //将数组拆分为长度为2的数组
  8. const arr= _.chunk(['a', 'b', 'c', 'd'], 2);
  9. return arr;
  10. }

Right-click lodash cloud function directory, select "Open in terminal", npm install install module after right-click deployment and upload all files. W e can call it in a number of ways (detailed earlier) to get results. Lodash is very useful and useful as a tool, its source code is also very worth learning, and more related content needs to go to Github and official technical documentation to learn more.

On the awesome Nodejs page we learned that there are similar tools libraries such as Ramba, immutable, and Mout, which are highly recommended. With Github's awesome list, we can master the coolest and most useful open source projects with one hand, avoiding collecting our own collections.