bootstrap.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'reflect-metadata';
  2. import { ConnectionOptions, createConnection, useContainer as typeOrmUseContainer } from 'typeorm';
  3. import * as express from 'express';
  4. import * as bodyParser from 'body-parser';
  5. import { graphqlExpress } from 'apollo-server-express';
  6. import { makeExecutableSchema } from 'graphql-tools';
  7. import { Container } from 'typedi';
  8. import { useContainer as typeGraphQlUseContainer, buildSchema } from 'type-graphql';
  9. import { User } from './entities/User';
  10. import { UserResolver } from './resolvers/userResolver';
  11. import {populate} from '../testing/populate';
  12. export interface BootstrapOptions {
  13. host: string;
  14. port: number;
  15. username: string;
  16. password: string;
  17. database: string;
  18. synchronize?: boolean;
  19. logging?: boolean;
  20. }
  21. const PORT = 3000;
  22. // Set up dependency injection for TypeORM and TypeGraphQL
  23. typeOrmUseContainer(Container);
  24. typeGraphQlUseContainer(Container);
  25. const defaultConnectionOptions: ConnectionOptions = {
  26. type: 'mysql',
  27. entities: ['./**/entities/*.ts'],
  28. synchronize: true,
  29. logging: false,
  30. };
  31. export async function bootstrap(options: BootstrapOptions) {
  32. try {
  33. const connectionOptions = {
  34. ...defaultConnectionOptions,
  35. ...options,
  36. } as ConnectionOptions;
  37. const connection = await createConnection(connectionOptions);
  38. populate(connection);
  39. const schema = await buildSchema({
  40. resolvers: [UserResolver],
  41. });
  42. const app = express();
  43. app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
  44. app.listen(PORT);
  45. } catch (error) {
  46. console.log(error);
  47. }
  48. }