Egg.js的方法扩展

Extend-application 方法扩展

eggjs的方法的扩展和编写

Egg.js可以对内部的五种对象进行扩展,以下是可扩展的对象、说明、this指向和使用方式。

application对象方法拓展

按照Egg的约定,扩展的文件夹和文件的名字必须是固定的。比如要对application扩展,要在/app目录下,新建一个/extend文件夹,然后在建立一个application.js文件。

javascript 复制代码
module.exports = {
  // 方法扩展
  currentTime() {
    const current = getTime();
    return current;
  },
};
function getTime() {
  const now = new Date();
  const year = now.getFullYear(); // 得到年份
  const month = now.getMonth() + 1; // 得到月份
  const date = now.getDate(); // 得到日期
  const hour = now.getHours(); // 得到小时数
  const minute = now.getMinutes(); // 得到分钟数
  const second = now.getSeconds(); // 得到秒数
  const nowTime = year + '年' + month + '月' + date + '日 ' + hour + ':' + minute + ':' + second;
  return nowTime;
}

使用:

javascript 复制代码
// .js
async index() {
  const { ctx ,app } = this;
  await ctx.render(
    'zhuba.html',{
      nowTime: app.currentTime()
    })
}
// .html 模板
<%= nowTime %>

application对象属性拓展

对属性( property) 的扩展的关键字是get,也需要写在application.js文件里。

javascript 复制代码
module.exports = {
    //方法扩展
    currentTime(){
        const current = getTime();
        return current;
    },
    //属性扩展
    get timeProp(){
        return getTime();
    }
};

加入get,就会默认是一个属性,可以直接以属性的形式在controller方法里进行调用。

Extend-context 上下文对象的方法拓展

之前通过上下文来获取传递参数时,get方法请求和post方法请求的获取方式是不同的,我们编写的方法可以让这两个请求获取参数的方法统一化,都用params( )方法。新建context.js,配置好页面和路由后使用

javascript 复制代码
// context.js
module.exports = {
  params(key) {
    const method = this.request.method
    if (method === 'GET') {
      return key ? this.query[key] : this.query;
    }
    return key ? this.request.body[key] : this.request.body;
  },
};

// newContext zhuba.js
async newContext() {
  const {
    ctx,
  } = this;
  const params = ctx.params();
  console.log(params);
  ctx.body = 'newContext';
}
// router.js
router.get('/newContext', controller.zhuba.newContext);
router.post('/newContext', controller.zhuba.newContext);

Extend-request

Request 中的扩展一般是扩展的属性。比如扩展 Request 中的一个属性,通过属性直接得到请求头中的 token 属性。

javascript 复制代码
// Extend-request
  async newRequest() {
    const {
      ctx,
    } = this;
    const token = ctx.request.token;
    ctx.body = {
      status: 200,
      body: token,
    };
  }

Egg.js 对 Request 的扩展也需要在/app/extend文件夹下,新建一个request.js文件,然后在这个文件里写扩展属性。

javascript 复制代码
module.exports = {
  get token() {
    console.log('token', this.get('token'));
    return this.get('token');
  },
};
// http测试
POST http://127.0.0.1:7001/newRequest
Content-Type: application/json
token: 'zhuba'

{
    "name":"小红",
    "age":18
}

response

和上一个是差不多的, 需要设置的方法以set关键字开头,然后用this.set( )就可以设置返回的token了。

javascript 复制代码
module.exports = {
  set token(token) {
    this.set('token', token);
  },
};

// zhuba.js
// newRespose
async newResponse() {
  const {
    ctx,
  } = this;
  ctx.response.token = 'zhuba.cloud';
  ctx.body = 'newRespose';
}
// router.js
router.get('/newResponse', controller.zhuba.newResponse);

helper

demo是编写一个字符串进行base64加密的方法。

javascript 复制代码
module.exports = {
  base64Encode(str = '') {
    return new Buffer(str).toString('base64');
  },
};

// 重新利用一下原本的 newRespose
// newRespose
async newResponse() {
  const {
    ctx,
  } = this;
  ctx.response.token = 'zhuba.cloud';
  // ctx.body = 'newRespose';
  const testBase64 = ctx.helper.base64Encode('zhuba.cloud');
  ctx.body = testBase64;
}

定时任务编写

定时任务需要按照Egg的约定,/app目录下,新建shedule文件夹。然后在shedule文件夹下,新建一个get_time.js文件。设置每3秒钟,在控制台输出当前时间戳。

javascript 复制代码
const Subscription = require('egg').Subscription;

class GetTime extends Subscription {
  static get schedule() {
    return {
      interval: '10s',
      type: 'worker',
    };
  }

  async subscribe() {
    console.log(Date.now());
  }
}

module.exports = GetTime;

也可以使用更复杂的cron属性进行定时。cron属性有6个参数。

javascript 复制代码
*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, optional)

比如设置每3秒钟,返回时间戳,可以写成下面的样子。

static get schedule(){
  return {
    cron: '*/3 * * * * *',
    type:'worker'
  };
}
相关推荐
迅猛龙办公室14 分钟前
python实现倒序输出数字
开发语言·python
夏幻灵6 小时前
JavaScript this 面试:五种绑定规则、优先级与常见面试陷阱
开发语言·javascript·面试
程序猿编码6 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
三天不学习7 小时前
Egg.js 4 突然爆火,原因是否归结于AI 原生落地需求爆发?
前端·javascript·全栈·egg.js
xcs194057 小时前
前端 vue 的前端页面debugger 进不去
前端·javascript·vue.js
bkspiderx8 小时前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
程序员老陆8 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光8 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
码云数智-园园9 小时前
unique_ptr 还是 shared_ptr?C++ 智能指针选型与内存泄漏实战分析
java·开发语言
禾小西9 小时前
07丨Redis 哨兵机制:主库故障后,如何恢复服务?
java·开发语言·redis