使用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

相關文章
相關標籤/搜索