nginx njs npm hashids 模块使用


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

场景

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

参考代码

  • fix hashids 问题
    因为原始hahsids 是基于了set ,但是对于set支持有点问题,所以调整了(核心是... spread 的特性支持)
    https://github.com/rongfengliang/hashids.js
    https://github.com/rongfengliang/hashids.js/blob/master/src/hashids.ts#L61
  • 集成hashids 到njs 中
    项目使用了njs-typescript-starter 模版,很方便,详细代码参考github
    src/index.ts
 
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