-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgres.js
133 lines (120 loc) · 3.44 KB
/
Postgres.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const Sequelize = require("sequelize");
const configBD = require("../config.json");
const Ajv = require("ajv");
const merge = require("lodash.merge");
function connect(db) {
const sequelize = new Sequelize(
db,
configBD.postgres.user,
configBD.postgres.password,
{
host: configBD.postgres.server,
dialect: "postgres",
port: configBD.postgres.port,
operatorsAliases: false,
pool: configBD.postgres.pool,
logging: configBD.postgres.logging,
timezone: "America/Sao_Paulo"
}
);
return sequelize;
}
// https://github.com/epoberezkin/ajv
// https://github.com/sequelize/sequelize/issues/3698
const Schema = {
validator: schemaProp => {
return {
schema: obj => {
// use defaults was not enough for nested objects
const ajv = new Ajv();
obj = Schema.applyDefaultValues(obj, schemaProp);
var valid = ajv.validate(schemaProp, obj);
if (!valid) {
console.log(obj);
throw new Error(JSON.stringify(ajv.errors));
}
}
};
},
obj: object => {
Object.keys(object).forEach(key => {
if (typeof object[key] === "function") {
object[key] = object[key].call(this);
}
});
return {
type: "object",
additionalProperties: false,
properties: object
};
},
array: items => {
if (typeof items === "function") {
items = items.call(this);
}
return {
type: ["array", "null"],
additionalItems: false,
items: items,
default: []
};
},
toPlain: content => {
const types = {};
if (content.hasOwnProperty("type")) {
content = content.properties;
for (const obj in content) {
if (content.hasOwnProperty(obj)) {
let row = content[obj];
if (typeof row == "function") {
row = row.call(this);
}
if (row.type === "object") {
types[obj] = Schema.toPlain(row);
} else {
types[obj] = null;
if (row.hasOwnProperty("default")) {
types[obj] = row.default;
}
}
} else {
console.error(obj, "not found");
}
}
} else {
throw new Error("Not is scheme AJV valid");
}
return JSON.parse(JSON.stringify(types));
},
applyDefaultValues: (obj, schemaProp) => {
return merge(Schema.toPlain(schemaProp), obj);
},
DATE: {
instanceof: "Date",
default: null
},
STRING: (def = "") => {
return {
type: ["string", "null"],
default: def
};
},
NUMBER: {
type: ["number", "null"],
default: null
},
ARRAY: {
type: ["array", "null"],
default: []
},
OBJECT: {
type: ["object", "null"],
additionalProperties: true,
default: {}
},
BOOLEAN: {
type: "boolean",
default: false
}
};
module.exports = { connect, Sequelize, Schema };