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
|
import config from "./config";
import Sequelize from "sequelize";
import SequelizeAuto from "sequelize-auto";
import {
resolver,
defaultArgs,
defaultListArgs,
attributeFields
} from "graphql-sequelize";
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLString,
GraphQLInt,
GraphQLNonNull,
GraphQLList
} from "graphql";
const conf = config.db[process.env.NODE_ENV || "development"];
const auto = new SequelizeAuto(
conf.database,
conf.username,
conf.password,
config.auto
);
const tables = {
User: "users",
Payment: "payments"
};
const db = new Sequelize(conf.database, conf.username, conf.password, {
host: conf.host,
dialect: conf.dialect,
logging: false,
dialectOptions: { multipleStatements: true }
});
const gqlfields = {};
const gqltypes = {};
const p = lnrpc => {
return new Promise((resolve, reject) => {
return auto.run(() => {
Object.keys(tables).forEach(k => {
let t = tables[k];
let fields = {};
Object.keys(auto.tables[t]).forEach(f => {
let isKey = f === "id";
let rawtype = auto.tables[t][f].type.toLowerCase();
let type = Sequelize.STRING;
if (rawtype.match(/^int/)) type = Sequelize.INTEGER;
if (rawtype.match(/^date/)) type = Sequelize.DATE;
fields[f] = {
type: type,
field: f,
primaryKey: isKey,
autoIncrement: isKey
};
});
db[k] = db.define(k, fields, { tableName: t });
let typefields = {};
let options = {};
if (t === "users") {
options = {
before: (findOptions, args, context) => {
findOptions.where = { id: context.user.id };
return findOptions;
}
};
}
if (t === "payments") {
db["Payment"].belongsTo(db["User"], {
as: "user",
foreignKey: "user_id"
});
options = {
before: (findOptions, args, context) => {
findOptions.where = { user_id: context.user.id };
return findOptions;
}
};
}
gqltypes[t] = new GraphQLObjectType({
name: t,
desc: t,
fields: Object.assign(typefields, attributeFields(db[k]))
});
gqlfields[t] = {
type: new GraphQLList(gqltypes[t]),
args: Object.assign({}, defaultArgs(db[k]), defaultListArgs()),
resolve: resolver(db[k], options)
};
});
db.gqlschema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "RootQueryType",
fields: gqlfields
})
});
resolve(db);
});
});
};
module.exports = p;
|