-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproject.js
More file actions
339 lines (289 loc) · 10.3 KB
/
project.js
File metadata and controls
339 lines (289 loc) · 10.3 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import * as telegram from '../utils/telegram';
const mongo = require('../mongo');
const { ApolloError, UserInputError } = require('apollo-server-express');
const Validator = require('../utils/validator');
const UserInProject = require('../models/userInProject');
const EventsFactory = require('../models/eventsFactory');
const ProjectToWorkspace = require('../models/projectToWorkspace');
const { dateFromObjectId } = require('../utils/dates');
const ProjectModel = require('../models/project').default;
const EVENTS_GROUP_HASH_INDEX_NAME = 'groupHashUnique';
const REPETITIONS_GROUP_HASH_INDEX_NAME = 'groupHash_hashed';
const REPETITIONS_USER_ID_INDEX_NAME = 'userId';
const MAX_SEARCH_QUERY_LENGTH = 50;
/**
* See all types and fields here {@see ../typeDefs/project.graphql}
*/
module.exports = {
Query: {
/**
* Returns project's Model
* @param {ResolverObj} _obj
* @param {String} projectId - project id
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<ProjectDBScheme>}
*/
async project(_obj, { projectId }, { factories }) {
return factories.projectsFactory.findById(projectId);
},
},
Mutation: {
/**
* Creates project
*
* @param {ResolverObj} _obj
* @param {string} workspaceId - workspace ID
* @param {string} name - project name
* @param {string} image - project logo
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Project[]}
*/
async createProject(_obj, { workspaceId, name, image }, { user, factories }) {
const workspace = await factories.workspacesFactory.findById(workspaceId);
if (!workspace) {
throw new UserInputError('No such workspace');
}
const options = {
name,
workspaceId,
uidAdded: user.id,
image,
};
const project = await factories.projectsFactory.create(options);
/**
* Create collections for storing events and setup indexes
*/
const projectEventsCollection = await mongo.databases.events.createCollection('events:' + project._id);
const projectRepetitionsEventsCollection = await mongo.databases.events.createCollection('repetitions:' + project._id);
await mongo.databases.events.createCollection('dailyEvents:' + project._id);
await projectEventsCollection.createIndex({
groupHash: 1,
},
{
unique: true,
name: EVENTS_GROUP_HASH_INDEX_NAME,
});
await projectRepetitionsEventsCollection.createIndex({
groupHash: 'hashed',
},
{
name: REPETITIONS_GROUP_HASH_INDEX_NAME,
});
await projectRepetitionsEventsCollection.createIndex({
'payload.user.id': 1,
}, {
name: REPETITIONS_USER_ID_INDEX_NAME,
sparse: true,
});
telegram.sendMessage(`🤯 Project ${name} was created`);
return project;
},
/**
* Update project settings
*
* @param {ResolverObj} _obj
* @param {string} projectId - id of the updated project
* @param {string} name - project name
* @param {string} description - project description
* @param {string} - project logo
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Project}
*/
async updateProject(_obj, { id, name, description, image }, { user, factories }) {
if (!Validator.string(name)) {
throw new UserInputError('Invalid name length');
}
if (!Validator.string(description, 0)) {
throw new UserInputError('Invalid description length');
}
const project = await factories.projectsFactory.findById(id);
if (!project) {
throw new ApolloError('There is no project with that id');
}
if (project.workspaceId.toString() === '6213b6a01e6281087467cc7a') {
throw new ApolloError('Unable to update demo project');
}
try {
const options = {
name,
description,
};
if (image) {
options.image = image;
}
return project.updateProject(options);
} catch (err) {
throw new ApolloError('Something went wrong');
}
},
/**
* Generates new project integration token by id
*
* @param {ResolverObj} _obj - default resolver object
* @param {string} id - id of the project in which the token field is being regenerated
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Object}
*/
async generateNewIntegrationToken(_obj, { id }, { factories }) {
const project = await factories.projectsFactory.findById(id);
if (!project) {
throw new ApolloError('There is no project with that id:', id);
}
const integrationId = project.integrationId || ProjectModel.generateIntegrationId();
const encodedIntegrationToken = ProjectModel.generateIntegrationToken(integrationId);
try {
const updatedProject = await project.updateProject({
token: encodedIntegrationToken,
integrationId,
});
return {
recordId: updatedProject._id,
record: updatedProject,
};
} catch (err) {
throw new ApolloError('Can\'t update integration token', err);
}
},
/**
* Remove project
*
* @param {ResolverObj} _obj
* @param {string} projectId - id of the updated project
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Promise<boolean>}
*/
async removeProject(_obj, { projectId }, { user, factories }) {
const project = await factories.projectsFactory.findById(projectId);
if (!project) {
throw new ApolloError('There is no project with that id');
}
if (project.workspaceId.toString() === '6213b6a01e6281087467cc7a') {
throw new ApolloError('Unable to remove demo project');
}
const workspaceModel = await factories.workspacesFactory.findById(project.workspaceId.toString());
/**
* Remove project events
*/
await new EventsFactory(project._id).remove();
/**
* Remove project from workspace
*/
await new ProjectToWorkspace(workspaceModel._id.toString()).remove(project._id);
/**
* Remove project
*/
await project.remove();
return true;
},
/**
* Updates user visit time on project and returns it
*
* @param {ResolverObj} _obj
* @param {String} projectId - project ID
* @param {Context.user} user - current authorized user {@see ../index.js}
* @return {Promise<Number>}
*/
async updateLastProjectVisit(_obj, { projectId }, { user }) {
const userInProject = new UserInProject(user.id, projectId);
return userInProject.updateLastVisit();
},
},
Project: {
/**
* Returns project creation date
*
* @param {ProjectDBScheme} project - result of parent resolver
*
* @returns {Date}
*/
creationDate(project) {
return dateFromObjectId(project._id);
},
/**
* Find project's event
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {String} eventId - event's identifier
*
* @returns {Event}
*/
async event(project, { id: eventId }) {
const factory = new EventsFactory(project._id);
const event = await factory.findById(eventId);
if (!event) {
return null;
}
event.projectId = project._id;
return event;
},
/**
* Find project events
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {number} limit - query limit
* @param {number} skip - query skip
* @param {Context.user} user - current authorized user {@see ../index.js}
* @returns {Event[]}
*/
async events(project, { limit, skip }) {
const factory = new EventsFactory(project._id);
return factory.find({}, limit, skip);
},
/**
* Returns events count that wasn't seen on project
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Object} data - additional data. In this case it is empty
* @param {User} user - authorized user
*
* @return {Promise<number>}
*/
async unreadCount(project, data, { user }) {
const eventsFactory = new EventsFactory(project._id);
const userInProject = new UserInProject(user.id, project._id);
const lastVisit = await userInProject.getLastVisit();
return eventsFactory.getUnreadCount(lastVisit);
},
/**
* Returns recent Events grouped by day
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Number} limit - limit for events count
* @param {Number} skip - certain number of documents to skip
* @param {'BY_DATE' | 'BY_COUNT'} sort - events sort order
* @param {EventsFilters} filters - marks by which events should be filtered
* @param {String} search - search query
*
* @return {Promise<RecentEventSchema[]>}
*/
async recentEvents(project, { limit, skip, sort, filters, search }) {
if (search) {
if (search.length > MAX_SEARCH_QUERY_LENGTH) {
search = search.slice(0, MAX_SEARCH_QUERY_LENGTH);
}
}
const factory = new EventsFactory(project._id);
return factory.findRecent(limit, skip, sort, filters, search);
},
/**
* Returns data about how many events accepted at each of passed N days
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Number} days - how many days we need to fetch for displaying in a charts
* @param {number} timezoneOffset - user's local timezone offset in minutes
*
* @return {Promise<ProjectChartItem[]>}
*/
async chartData(project, { days, timezoneOffset }) {
const factory = new EventsFactory(project._id);
return factory.findChartData(days, timezoneOffset);
},
},
};