nginx njs npm hashids 模块使用

主要是将今天说到的工具做一个使用说明

场景

直接复用npm 的hashids 生成一个id,同时基于rollup 构建,对于缺少js 特性支持的基于core-js 进行polyfill

参考代码

 
import 'core-js/actual/array/from';
import 'core-js/actual/set'; 
 
import { hello,token } from './hello'
 
// NOTE: This module must contain only the default export, no named exports!
 
export default {
  hello,
  token
}

hello.ts

import qs from 'querystring'
// 使用自己修改的hashids 服务
import hashids  from '@dalongrong/hashids'
 
export function hello (r: NginxHTTPRequest): void {
  const name = r.args.name ? qs.unescape(r.args.name) : 'world'
 
  return r.return(200, `
    Meow, ${name}!
 
        ("\`-''-/").___..--''"\`-._
        \`6_ 6  )   \`-.  (     ).\`-.__.\`)
        (_Y_.)'  ._   )  \`._ \`. \`\`-..-'
      _..\`--'_..-_/  /--'_.' ,'
      (il),-''  (li),'  ((!.-'
  `)
}
export function token(r: NginxHTTPRequest):void {
  let myhashids = new hashids("demoapp",10).encode(Math.floor(Math.random()*4000));
  return r.return(200,myhashids)
}
  • njs 集成使用
js_import /opt/jsapp/main.js;
 
location = /token {
          js_content main.token;
}

效果

 

 

说明

以上是工具集成的一个使用说明,实际上目前njs 还没有openresty 强大,功能上还是比较简单的,但是基于npm 扩展还可以暂时弥补一部分缺少的功能,期待
更加强大

参考资料

https://github.com/jirutka/babel-preset-njs
https://github.com/jirutka/njs-typescript-starter
https://github.com/jirutka/nginx-testing
https://github.com/rongfengliang/hashids.js
https://github.com/rongfengliang/nginx-njs-learning/tree/1.21.5

posted on 2022-05-28 21:04  荣锋亮  阅读(351)  评论(0编辑  收藏  举报

导航