forked from ziaochina/mk-service-db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
95 lines (80 loc) · 2.63 KB
/
api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const Sequelize = require("sequelize")
const cls = require('continuation-local-storage')
Sequelize.useCLS(cls.createNamespace('my-own-namespace'))
let current = null
const dbs = {}
const api = {
currentDB: null,
getDB: (name) => dbs[name || 'currentDB'],
_init: (options) => {
current = options
dbs.currentDB = dbs[current.name] = newDB(current)
dbs.currentDB.config.transactionType = current.transactionType
if (Array.isArray(current.dbs)) {
current.dbs.filter(d => !dbs[d.name]).forEach(d => {
dbs[d.name] = newDB(d);
dbs[d.name].config.transactionType = d.transactionType
})
}
if (current.server) { //注册数据库事务拦截器
var array = current.server.interceptors || [];
if (array.filter(a => a == interceptor) == 0) {
array.push(interceptor)
}
current.server.interceptors = array
}
}
}
function newDB(cfg) {
return new Sequelize(cfg.database, cfg.user, cfg.pwd, {
host: cfg.host,
port: cfg.port,
dialect: cfg.type,
})
}
function interceptor(ctx) {
var currentDB = null;
var serviceConfig = ctx.service.config && ctx.service.config.current;
var transactionType = ctx.handler.transactionType
|| serviceConfig && serviceConfig.transactionType
|| serviceConfig && serviceConfig.db && serviceConfig.db.config.transactionType;
if (serviceConfig && serviceConfig.db) {
currentDB = serviceConfig.db
}
transactionType = transactionType || current.transactionType
currentDB = currentDB || dbs.currentDB
if (currentDB && transactionType == 'auto' && !ctx._handler) {
var transactionWrapper = function () {
return currentDB.transaction((t) =>
ctx._handler(...arguments)
)
}
ctx._handler = ctx.handler
ctx.handler = transactionWrapper
Object.assign(transactionWrapper, ctx._handler)
}
return true
}
/*
* config.js //初始化参数设置
*/
function config(options) {
let current = config.current
Object.assign(current, options)
if (!options.host && options.dbs) {
Object.assign(current, current.dbs[0])
}
api._init(current)
}
config.current = {
name: "bizdata",
type: "mysql",
user: "root",
pwd: "mydbpassword",
host: "localhost",
port: 3306,
database: "bizdata_dev",
transactionType: "auto",
dbs: [],
}
module.exports = { api, config }