|
| 1 | +import * as mongoose from 'mongoose'; |
| 2 | +import MongoDBInterface from '@accounts/mongo'; |
| 3 | +import { AccountsPassword } from '@accounts/password'; |
| 4 | +import { AccountsServer } from '@accounts/server'; |
| 5 | +import { ApolloServer, makeExecutableSchema } from 'apollo-server'; |
| 6 | +import { DatabaseManager } from '@accounts/database-manager'; |
| 7 | +import { createAccountsGraphQL, accountsContext } from '@accounts/graphql-api'; |
| 8 | + |
| 9 | +const start = async () => { |
| 10 | + // Create database connection |
| 11 | + let storage; |
| 12 | + if (process.env.ACCOUNTS_DB === 'mongo') { |
| 13 | + await mongoose.connect(process.env.ACCOUNTS_DB_URL, { useNewUrlParser: true }); |
| 14 | + storage = new MongoDBInterface(mongoose.connection); |
| 15 | + } |
| 16 | + |
| 17 | + // Build a storage for storing users |
| 18 | + // Create database manager (create user, find users, sessions etc) for accounts-js |
| 19 | + const accountsDb = new DatabaseManager({ |
| 20 | + sessionStorage: storage, |
| 21 | + userStorage: storage, |
| 22 | + }); |
| 23 | + |
| 24 | + // Create accounts server that holds a lower level of all accounts operations |
| 25 | + const accountsServer = new AccountsServer( |
| 26 | + { db: accountsDb, tokenSecret: process.env.ACCOUNTS_SECRET }, |
| 27 | + { password: new AccountsPassword() }, |
| 28 | + ); |
| 29 | + |
| 30 | + // Creates resolvers, type definitions, and schema directives used by accounts-js |
| 31 | + const accountsGraphQL = createAccountsGraphQL(accountsServer, { extend: false }); |
| 32 | + |
| 33 | + const schema = makeExecutableSchema({ |
| 34 | + resolvers: { Query: {}, ...accountsGraphQL.resolvers }, |
| 35 | + schemaDirectives: accountsGraphQL.schemaDirectives, |
| 36 | + typeDefs: [accountsGraphQL.typeDefs], |
| 37 | + }); |
| 38 | + |
| 39 | + // Create the Apollo Server that takes a schema and configures internal stuff |
| 40 | + const server = new ApolloServer({ |
| 41 | + schema, |
| 42 | + context: ({ req }) => accountsContext(req, { accountsServer }), |
| 43 | + }); |
| 44 | + |
| 45 | + server.listen(4000).then(({ url }) => { |
| 46 | + console.log(`🚀 Server ready at ${url}`); |
| 47 | + }); |
| 48 | +}; |
| 49 | + |
| 50 | +start(); |
0 commit comments