preface
Egg.js regular task backup wechat small program cloud development database, here is just a simple implementation, verify the validity of the method, the code is messy, if necessary, you can tidy up the code under the Service for your own use. [node.js] [node.js] [node.js] [node.js] [node.js] 【 Welcome star】
code
config/config.default.js
'use strict';
/ * * *@param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo= > {
/**
* built-in config
* @type {Egg.EggAppConfig}* * /
const config = exports = {};
// Wechat related parameters
config.wx = {
appid: process.env.wx_appid,
secret: process.env.wx_secret,
env: process.env.wx_env, // Cloud environment ID
};
// Tencent cloud COS parameters
config.cos = {
secretId: process.env.cos_secretId,
secretKey: process.env.cos_secretKey,
bucket: process.env.cos_bucket,
region: process.env.cos_region,
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1637136443161_2316';
config.cors = {
origin: The '*'.allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'};// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return{... config, ... userConfig, }; };Copy the code
controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
const result = await ctx.service.home.index();
ctx.logger.info('Active backup triggered by URL, result: %j', result.statusCode); ctx.body = result.statusCode; }}module.exports = HomeController;
Copy the code
schedule/export.js
const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
// Use the schedule attribute to set the execution interval of scheduled tasks
static get schedule() {
return {
interval: '0, 10, 2 * *, right? '.// Run once every day at 2:10
type: 'all'.// specify that all workers need to be executed
};
}
// subscribe is the function that is run when the actual scheduled task is executed
async subscribe() {
const { ctx } = this;
const result = await ctx.service.home.index();
ctx.logger.info('Scheduled task execution message reminder result: %j', result.statusCode); }}module.exports = UpdateCache;
Copy the code
service/home.js
'use strict';
const dayjs = require('dayjs');
const COS = require('cos-nodejs-sdk-v5');
const Service = require('egg').Service;
const file_path = `${dayjs().format('YYYY-MM-DD HH:mm:ss')}.json`;
const url = 'https://api.weixin.qq.com/';
class Index extends Service {
async index() {
const { ctx, config: { wx } } = this;
/ / get access_token
const { data: { access_token } } = await ctx.curl(`${url}cgi-bin/token? grant_type=client_credential&appid=${wx.appid}&secret=${wx.secret}`, {
dataType: 'json'});if(! access_token)return { statusCode: 400 };
/ / get job_id
const { data: { job_id } } = await ctx.curl(`${url}tcb/databasemigrateexport? access_token=${access_token}`, {
method: 'POST'.contentType: 'json'.data: {
env: wx.env,
file_path,
file_type: '1'.query: 'db.collection("SecretList").get()'.// You can also write your own data
},
dataType: 'json'});if(! job_id)return { statusCode: 400 };
return await this.firmwareTimer(access_token, job_id);
}
async firmwareTimer(access_token, job_id) {
const { ctx, config: { wx, cos } } = this;
const cloudCos = new COS({
SecretId: cos.secretId,
SecretKey: cos.secretKey,
});
// The export task takes time to complete. The larger the data is, the more time is needed. In my case, the 200K data takes about 5-10s
return new Promise(resolve= > {
let count = 10;
let firmwareTimer = setInterval(async () => {
count -= 1; // Prevent setInterval from being used for a long time. It is automatically cleared after 10 times
// Get the file from job_id
const { data: { status, file_url } } = await ctx.curl(`${url}tcb/databasemigratequeryinfo? access_token=${access_token}`, {
method: 'POST'.contentType: 'json'.data: {
env: wx.env,
job_id,
},
dataType: 'json'});if (status === 'success') {
clearInterval(firmwareTimer);
firmwareTimer = null;
const { data } = await ctx.curl(file_url);
// Upload to Tencent Cloud OSS
cloudCos.putObject({
Bucket: cos.bucket,
Region: cos.region,
Key: `bt_backup/mfa-export-database/${file_path}`.Body: data,
}, function(err, data) {
resolve(err || data);
});
}
if (count) {
clearInterval(firmwareTimer);
firmwareTimer = null; }},5000); }); }}module.exports = Index;
Copy the code
reference
Egg – Online cron expression generation for enterprise frameworks and applications uses node.js process to hide important project parameters
conclusion
If you think this article is helpful to you, please like, comment and forward. First published in the finch documentation @is_tao