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