MCPcopy Create free account
hub / github.com/apollographql/fullstack-tutorial / UserAPI

Class UserAPI

start/server/src/datasources/user.js:4–81  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2const isEmail = require('isemail');
3
4class UserAPI extends DataSource {
5 constructor({ store }) {
6 super();
7 this.store = store;
8 }
9
10 /**
11 * This is a function that gets called by ApolloServer when being setup.
12 * This function gets called with the datasource config including things
13 * like caches and context. We'll assign this.context to the request context
14 * here, so we can know about the user making requests
15 */
16 initialize(config) {
17 this.context = config.context;
18 }
19
20 /**
21 * User can be called with an argument that includes email, but it doesn't
22 * have to be. If the user is already on the context, it will use that user
23 * instead
24 */
25 async findOrCreateUser({ email: emailArg } = {}) {
26 const email =
27 this.context && this.context.user ? this.context.user.email : emailArg;
28 if (!email || !isEmail.validate(email)) return null;
29
30 const users = await this.store.users.findOrCreate({ where: { email } });
31 return users && users[0] ? users[0] : null;
32 }
33
34 async bookTrips({ launchIds }) {
35 const userId = this.context.user.id;
36 if (!userId) return;
37
38 let results = [];
39
40 // for each launch id, try to book the trip and add it to the results array
41 // if successful
42 for (const launchId of launchIds) {
43 const res = await this.bookTrip({ launchId });
44 if (res) results.push(res);
45 }
46
47 return results;
48 }
49
50 async bookTrip({ launchId }) {
51 const userId = this.context.user.id;
52 const res = await this.store.trips.findOrCreate({
53 where: { userId, launchId },
54 });
55 return res && res.length ? res[0].get() : false;
56 }
57
58 async cancelTrip({ launchId }) {
59 const userId = this.context.user.id;
60 return !!this.store.trips.destroy({ where: { userId, launchId } });
61 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected