-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
249 lines (227 loc) · 6.34 KB
/
index.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const graphqlHTTP = require('express-graphql');
const { Sequelize, DataTypes } = require('sequelize');
const { makeExecutableSchema } = require('graphql-tools');
const { OAuth2Client } = require('google-auth-library');
const oauthClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
const googleAuth = async (idToken) => {
const ticket = await oauthClient.verifyIdToken({ idToken, audience: process.env.GOOGLE_CLIENT_ID });
const payload = ticket.getPayload();
const { sub } = payload;
return { googleID: sub };
}
const PORT = process.env.PORT || 5000;
const db = new Sequelize(process.env.DATABASE_URL);
const MyDataTypes = {
TablePrimaryKey: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
};
/**
* User
*/
const UserTable = db.define('User', {
uuid: MyDataTypes.TablePrimaryKey,
googleID: DataTypes.STRING,
votedProposals: { type: DataTypes.ARRAY(DataTypes.UUID), defaultValue: [] },
});
const UserGraphQLTypeDefinition = `
type User {
uuid: String!
}
`;
const UserRootField = {
definition: 'user: User',
resolver: {
user: async (_, __, context) => {
if (!context || !context.userId) {
return null;
}
return await UserTable.findOne({ where: { uuid: context.userId } });
},
},
};
const SigninMutation = {
definition: 'signin: Boolean',
resolver: {
signin: async (_, __, context) => {
if (!context || !context.userId) {
return false;
}
return true;
},
},
};
const DeleteAccountMutation = {
definition: 'deleteAccount: Boolean',
resolver: {
deleteAccount: async (_, __, context) => {
if (!context || !context.userId) {
return false;
}
await UserTable.destroy({ where: { uuid: context.userId } });
return true;
}
},
};
/**
* Standard Proposal
*/
const StandardProposalTable = db.define('StandardProposal', {
uuid: MyDataTypes.TablePrimaryKey,
version: DataTypes.STRING,
data: DataTypes.TEXT,
});
const StandardProposalGraphQLTypeDefinition = `
type StandardProposal {
uuid: String!
version: String!
data: String
}
`;
const StandardProposalRootField = {
defintion: `standardProposal: StandardProposal`,
resolver: {
standardProposal: async () => {
const standardProposals = await StandardProposalTable.findAll({
limit: 1,
order: [['createdAt', 'DESC']]
});
return standardProposals[0];
},
}
}
/**
* Proposal
*/
const ProposalTable = db.define('Proposal', {
uuid: MyDataTypes.TablePrimaryKey,
userId: DataTypes.UUID,
data: DataTypes.TEXT,
});
const ProposalGraphQLTypeDefinition = `
type Proposal {
uuid: String!
data: String
}
`;
const ProposalRootField = {
definition: 'proposal(uuid: String!): Proposal',
resolver: {
proposal: (_, { uuid }) => ProposalTable.findOne({ where: { uuid } }),
},
};
const ProposalsRootField = {
definition: 'proposals: [Proposal]',
resolver: {
proposals: () => ProposalTable.findAll(),
}
};
const AddProposalMutation = {
definition: 'addProposal(proposal: String): Proposal',
resolver: {
addProposal: async (_, { proposal }, context) => {
if (!context || !context.userId) {
return null;
}
const newProposal = await ProposalTable.create({ data: proposal, userId: context.userId });
return { uuid: newProposal.uuid, data: proposal };
}
},
};
const VoteProposalMutation = {
definition: 'voteProposal(proposalId: String!, position: Int): Boolean',
resolver: {
voteProposal: async (_, { proposalId, position }, context) => {
if (!context || !context.userId) {
return false;
}
const user = await UserTable.findOne({ where: { uuid: context.userId } });
const votedProposals = user.votedProposals != null ? user.votedProposals : [];
if (position == null || position <= 0) {
await user.update({
votedProposals: votedProposals.filter(id => id !== proposalId),
});
} else if (position > votedProposals.length) {
await user.update({
votedProposals: votedProposals.concat(proposalId),
});
} else {
await user.update({
votedProposals: votedProposals.slice().splice(position - 1, 0, id),
});
}
return true;
}
},
};
// Associations
UserTable.hasMany(ProposalTable);
ProposalTable.belongsTo(UserTable, { foreignKey: 'userId', onDelete: 'CASCADE' });
// Update all tables
db.sync({ alter: true });
async function createContext(req) {
const token = req.headers ? req.headers.authorization : null;
if (token === '' || token == null) {
return null;
};
try {
const { googleID } = await googleAuth(token);
let user = await UserTable.findOne({ where: { googleID } });
if (!user) {
user = await UserTable.create({ googleID });
}
return { userId: user.uuid };
} catch (e) {
console.log(e);
return null;
}
}
express()
.use(cors())
.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }))
.use(
'/graphql',
graphqlHTTP(async req => ({
schema: makeExecutableSchema({
typeDefs: `
${UserGraphQLTypeDefinition}
${ProposalGraphQLTypeDefinition}
${StandardProposalGraphQLTypeDefinition}
type Query {
${ProposalRootField.definition},
${ProposalsRootField.definition},
${StandardProposalRootField.defintion},
${UserRootField.definition},
}
type Mutation {
${AddProposalMutation.definition},
${SigninMutation.definition},
${DeleteAccountMutation.definition},
${VoteProposalMutation.definition},
}
`,
resolvers: {
Query: {
...ProposalRootField.resolver,
...ProposalsRootField.resolver,
...StandardProposalRootField.resolver,
...UserRootField.resolver,
},
Mutation: {
...AddProposalMutation.resolver,
...SigninMutation.resolver,
...DeleteAccountMutation.resolver,
...VoteProposalMutation.resolver,
},
},
}),
context: await createContext(req),
graphiql: true,
})))
.listen(PORT, () => console.log(`Listening on ${PORT}`))