使用plv8+ shortid npm包构建一个短惟一id服务

plv8 是一个很强大的pg 扩展插件,咱们能够直接额使用js 加强sql ,shortid 是一个用来生成短链接id 很方便的类库
由于shortid 是一个npm 模块,咱们须要使用一种方法使用require 的方式引用包,这个咱们能够经过 plv8 node 模块解决
如下是一个简单的demonode

使用plv8 node 模块注册shortid 原理

使用plv8 node 模块主要是方便快速的生成plv8 pg 插件可以使用的npm 包(包含依赖的处理,基于browserify的处理)
原理实际上比较简单,主要包含如下git

  • 生成包含依赖的js
browserify +bable node api
  • require 的钩子
    基于plv8 提供的plv8.start_proc,同时咱们经过数据级别的session 配置简单应用端链接须要的set 执行
    参考以下:
ALTER DATABASE postgres SET "plv8.start_proc" TO "v8.plv8_init";
  • 基于plv8 建立 调用shortid 的函数
    内容以下:
 
CREATE or replace FUNCTION shortid() RETURNS text AS
$$
   const shortid = require('shortid');
   const result = shortid.generate();
   return result;
$$
LANGUAGE plv8;

注册shortid demo

  • package.json
{
  "name": "node-plv8",
  "version": "1.0.0",
  "main": "app.js",
  "bin": "app.js",
  "license": "MIT",
  "dependencies": {
    "cuid": "^2.1.6",
    "knex": "^0.20.1",
    "lodash": "^4.17.15",
    "pg": "^7.12.1",
    "plv8": "^2.1.4",
    "shortid": "^2.2.15",
    "uuid": "^3.3.3"
  },
  "scripts": {
    "init:app": "node app"
  }
}
  • 调用plv8 npm 模块实现npm包注册
// setup plv8 connection
const PLV8 = require('plv8')
const knex = require('knex')
const knexHandle = knex({
    client: 'pg',
    connection: {
      host: "127.0.0.1",
      user: "postgres",
      password: "dalong",
      database: "postgres"
    }
  })
const plv8 = new PLV8(knexHandle)
// setup a log listener
plv8.on('log:error', msg => {
  console.error(msg)
})
  plv8.install({modulePath:require.resolve("shortid"),moduleName:"shortid"})
  .then(() => {
    // eval some code
    return plv8.eval(() => {
      const shortid = require('shortid')
      return shortid.generate()
    })
  })
  .then(result => {
   console.log(result)
  }).catch(err=>{
      console.log(err)
  })

短链接服务模型

为了演示,模型比较简单,主要是一个自增id 以及shortid 的存储,shortid 的生成经过调用
咱们建立的函数shortidgithub

  • 数据库表
 
CREATE TABLE shortids (
    id integer DEFAULT nextval('shorids_id_seq'::regclass) PRIMARY KEY,
    shortid text
);
-- Indices -------------------------------------------------------
CREATE UNIQUE INDEX shorids_pkey ON shortids(id int4_ops);
 
 
  • 插入操做
insert into shortids(shortid) values(shortid());
  • 数据效果

 

 

说明

从shortid 的算法上,随机性比较高的,通常的猜想比较难,咱们经过plv8 以及强大的js能力,很方便的就能够设计一个灵活的短链接服务算法

参考资料

http://knexjs.org/#Installation-pooling
https://github.com/langateam/node-plv8
https://github.com/plv8/plv8
https://github.com/dylang/shortid
https://github.com/rongfengliang/plv8-require-learningsql

相关文章
相关标签/搜索