@nestjs/graphql#GraphQLModule TypeScript Examples

The following examples show how to use @nestjs/graphql#GraphQLModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: typegraphql.module.ts    From typegraphql-nestjs with MIT License 6 votes vote down vote up
static forRoot(options: TypeGraphQLRootModuleOptions = {}): DynamicModule {
    const dynamicGraphQLModule = GraphQLModule.forRootAsync({
      useClass: TypeGraphQLOptionsFactory,
    });
    return {
      ...dynamicGraphQLModule,
      providers: [
        ...dynamicGraphQLModule.providers!,
        OptionsPreparatorService,
        {
          provide: TYPEGRAPHQL_ROOT_MODULE_OPTIONS,
          useValue: options,
        },
      ],
    };
  }
Example #2
Source File: app.module.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UserModule,
    DummyModule,
    GraphQLModule.forRoot({
      driver: ApolloDriver,
      installSubscriptionHandlers: true,
      autoSchemaFile: '~schema.gql',
    }),
  ],
})
export class AppModule {}
Example #3
Source File: starwars.module.ts    From nestjs-relay with MIT License 6 votes vote down vote up
@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: './test/starwars-app/schema.gql',
    }),
  ],
  providers: [
    FactionResolver,
    FactionService,
    NodeResolver,
    ShipResolver,
    ShipService,
    GlobalIdScalar,
  ],
})
export class StarWarsModule {}
Example #4
Source File: app.module.ts    From game-store-monorepo-app with MIT License 6 votes vote down vote up
@Module({
  imports: [
    HttpModule,
    ConfigModule,
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
    }),
  ],
  providers: [GameResolver, GenreResolver, TagResolver, PublisherResolver],
})
export class AppModule {}
Example #5
Source File: notification-test.imports.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
NotificationTestImports = [
  ConfigModule.forRoot(),
  GraphQLModule.forRoot({
    autoSchemaFile: true,
  }),
  DynamooseModule.forRoot({
    local: 'http://localhost:8001',
    aws: { region: 'local' },
    model: {
      create: false,
      prefix: `${process.env.SERVICE}-${process.env.STAGE}-`,
      suffix: '-table',
    },
  }),
  DynamooseModule.forFeature([
    {
      name: 'notification',
      schema: NotificationSchema,
    },
  ]),
]
Example #6
Source File: app.module.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot(),
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      playground: {
        endpoint:
          process.env.IS_NOT_SLS === 'true'
            ? '/graphql'
            : `/${process.env.STAGE}/graphql`,
      },
    }),
    DynamooseModule.forRoot({
      local: process.env.IS_DDB_LOCAL === 'true',
      aws: { region: process.env.REGION },
      model: {
        create: false,
        prefix: `${process.env.SERVICE}-${process.env.STAGE}-`,
        suffix: '-table',
      },
    }),
    NotificationModule,
  ],
})
export class AppModule {}
Example #7
Source File: graphql.e2e.spec.ts    From nest-casl with MIT License 6 votes vote down vote up
createCaslTestingModule = async (
  caslOptions: OptionsForRoot<Roles>,
  postService: PostService,
  userService: UserService,
): Promise<INestApplication> => {
  const moduleRef = await Test.createTestingModule({
    imports: [
      PostModule,
      UserModule,
      GraphQLModule.forRoot<ApolloDriverConfig>({
        driver: ApolloDriver,
        autoSchemaFile: true,
        playground: false,
        debug: true,
      }),
      CaslModule.forRoot<Roles>(caslOptions),
    ],
  })
    .overrideProvider(PostService)
    .useValue(postService)
    .overrideProvider(UserService)
    .useValue(userService)
    .compile();

  const app = moduleRef.createNestApplication();
  await app.init();
  return app;
}
Example #8
Source File: app.module.ts    From nest-casl with MIT License 6 votes vote down vote up
@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: true,
      useGlobalPrefix: false,
      playground: false,
      context: ({ req }) => ({ req }),
    }),
    CaslModule.forRoot<Roles>({
      superuserRole: Roles.admin,
      getUserFromRequest(request) {
        return request.user;
      },
      getUserHook: UserHook,
    }),
    UserModule,
    PostModule,
  ],
})
export class AppModule {}
Example #9
Source File: app.module.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
@Module({
  imports: [
    GraphQLModule.forRoot(graphqlConfig),
    ClientsModule.register([
      {
        name: 'MAIN_SERVICE',
        transport: Transport.TCP,
        options: {
          ...TracingModule.getParserOptions(),
        },
      },
      {
        name: 'MATH_SERVICE',
        transport: Transport.TCP,
        options: {
          port: 3001,
          ...TracingModule.getParserOptions(),
        },
      },
    ]),
    TracingModule.forRootAsync({
      useFactory: () => ({
        exporterConfig: {
          serviceName: 'core-service',
        },
        isSimpleSpanProcessor: true,
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService, AppResolver],
})
export class AppModule {}
Example #10
Source File: module.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Module({
  imports: [
    GraphQLModule.forRoot({
      introspection: Boolean(playground),
      playground,
      installSubscriptionHandlers: false,
      autoSchemaFile: 'schema.gql',
      path: '//',
      cors: false,
      context: ({ req }) => ({
        user: req.get('x-user'),
      }),
    }),
    IdentityModule,
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: DataLoaderInterceptor,
    },
  ],
})
export class ApplicationModule {}
Example #11
Source File: nestjs-apollo-testing.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps Apollo Server's createTestClient to easily work with Nest.js
 * @param testingModule the Nest.js testing module
 * @returns Apollo Server's test client
 */
export function createApolloServerTestClient(
  testingModule: TestingModule
): ApolloServerTestClient {
  // GraphQLModule doesn't expose the apolloServer property
  const graphqlModule = testingModule.get(GraphQLModule) as any;
  return createTestClient(graphqlModule.apolloServer);
}
Example #12
Source File: hello.module.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
@Module({
  imports: [
    GraphQLModule.forRoot({
      typePaths: [join(__dirname, '*.graphql')],
    }),
  ],
  providers: [
    HelloResolver,
    HelloService,
    UsersService,
    {
      provide: 'REQUEST_ID',
      useFactory: () => 1,
      scope: Scope.REQUEST,
    },
  ],
})
export class HelloModule {
  constructor(@Inject('META') private readonly meta) {}

  static forRoot(meta: Provider): DynamicModule {
    return {
      module: HelloModule,
      providers: [meta],
    };
  }
}
Example #13
Source File: typegraphql.module.ts    From typegraphql-nestjs with MIT License 6 votes vote down vote up
static forRootAsync(
    options: TypeGraphQLRootModuleAsyncOptions,
  ): DynamicModule {
    const dynamicGraphQLModule = GraphQLModule.forRootAsync({
      imports: options.imports,
      useClass: TypeGraphQLOptionsFactory,
    });
    return {
      ...dynamicGraphQLModule,
      providers: [
        ...dynamicGraphQLModule.providers!,
        OptionsPreparatorService,
        {
          inject: options.inject,
          provide: TYPEGRAPHQL_ROOT_MODULE_OPTIONS,
          useFactory: options.useFactory,
        },
      ],
    };
  }
Example #14
Source File: app.module.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
@Module({
  imports: [
    TypeOrmModule.forRoot(typeormConfig),
    // only if you are using GraphQL
    GraphQLModule.forRoot({
      autoSchemaFile: join(process.cwd(), 'src/infrastructure/schema.gql'),
    }),
    UnitOfWorkModule,
    NestEventModule,
    ConsoleModule,
    UserModule,
    WalletModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
Example #15
Source File: app.module.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Root module backend-api app
 */
@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...environment.connection,
      entities: [UserEntity],
    }),
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
      context: ({req}) => ({req}),
      playground: true,
      resolvers: [resolverMap],
    }),
    UsersModule,
    AuthModule,
  ],
  controllers: [AppController],
})
export class AppModule {
}
Example #16
Source File: app.module.ts    From whispr with MIT License 6 votes vote down vote up
@Module({
  imports: [
    TerminusModule,
    GraphQLModule.forRootAsync<ApolloDriverConfig>({
      imports: [ConfigModule],
      driver: ApolloDriver,
      useFactory: async (configService: ConfigService) => ({
        autoSchemaFile: configService.get('AUTO_SCHEMA_FILE'),
        introspection: configService.get('INTROSPECTION'),
        playground: false,
        cors: false,
        plugins: configService.get('PLAYGROUND') ? [ApolloServerPluginLandingPageLocalDefault()] : [],
        installSubscriptionHandlers: true,
      }),
      inject: [ConfigService],
    }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => configService.getMongooseOptions(),
      inject: [ConfigService],
    }),
    PubSubModule,
    WhispModule,
    TagGroupModule,
    TagModule,
    SequenceModule,
    ConfigModule,
    AWSCredsModule,
    FileModule,
    DistributionModule,
    EventModule,
    WebhookModule,
    AuthModule,
  ],
  providers: [AppService],
  controllers: [AppController, HealthController],
})
export class AppModule {}
Example #17
Source File: app.module.ts    From knests with MIT License 5 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      ignoreEnvFile: false,
    }),
    KnexModule.forRoot({
      config: {
        client: 'pg',
        debug: true,
        connection: process.env.DATABASE_URL,
        pool: { min: 0, max: 7, idleTimeoutMillis: 300_000 },
      },
    }),
    // schema first dev
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
      // installSubscriptionHandlers: true,
      installSubscriptionHandlers: false,
      debug: !isProduction,
      playground: !isProduction,
      context: ({ req }) => ({ req }),
      definitions: {
        path: join(process.cwd(), 'src/graphql.ts'),
        outputAs: 'class',
      },
    }),
    // this would be for "code first" development
    // GraphQLModule.forRoot({
    //   context: ({ req }) => ({ req }),
    //   autoSchemaFile: 'schema.gql',
    //   debug: !isProduction,
    //   playground: !isProduction,
    // }),
    AuthModule,
    UsersModule,
    AppService,
  ],
  controllers: [AppController],
  providers: [AppService],
})

export class AppModule implements OnModuleDestroy {

  @InjectKnex() private readonly knex: Knex;

  async onModuleDestroy() {
    await this.knex.destroy();
  }
}
Example #18
Source File: app.module.ts    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
@Module({
  imports: [
    MongooseModule.forRoot(MONO_DB_CONNECTION_STRING, {
      useCreateIndex: true,
      useNewUrlParser: true,
    }),
    MongooseModule.forFeature([...schemas]),
    GraphQLModule.forRoot({
      installSubscriptionHandlers: true,

      cors: {
        origin: CORS_ORIGIN,
        optionsSuccessStatus: 200,
        credentials: true,
      },
      plugins: [SentryPlugin],
      engine: {
        // The Graph Manager API key
        apiKey: ENGINE_API_KEY,
        // A tag for this specific environment (e.g. `development` or `production`).
        // For more information on schema tags/variants, see
        // https://www.apollographql.com/docs/platform/schema-registry/#associating-metrics-with-a-variant
        schemaTag: ENV,
      },
      autoSchemaFile: 'schema.gql',
      context: ({ req, res, connection }) => {
        const clientId = get(connection, 'context.clientId');
        return { req, res, ...(clientId && { clientId }) };
      },
    }),
    AuthModule,
    ChatModule,
    UserModule,
  ],
  controllers: [HealthzController],
  providers: [...services, ...resolvers],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('*');
  }
}
Example #19
Source File: app.imports.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
imports = [
  ConsoleModule,
  HttpModule.register({
    timeout: 5000,
    maxRedirects: 10,
  }),
  ServeStaticModule.forRoot({
    rootPath: join(__dirname, '..', 'public'),
    exclude: ['/graphql'],
  }),
  ConfigModule.forRoot({
    load: [
      () => {
        return {
          LOCALES_PATH: join(process.cwd(), 'locales'),
          SECRET_KEY: process.env.SECRET_KEY || crypto.randomBytes(20).toString('hex'),
        }
      },
    ],
  }),
  JwtModule.registerAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): JwtModuleOptions => ({
      secret: configService.get<string>('SECRET_KEY'),
      signOptions: {
        expiresIn: '4h',
      },
    }),
  }),
  LoggerModule.forRoot(LoggerConfig),
  GraphQLModule.forRoot<ApolloDriverConfig>({
    debug: process.env.NODE_ENV !== 'production',
    definitions: {
      outputAs: 'class',
    },
    driver: ApolloDriver,
    sortSchema: true,
    introspection: process.env.NODE_ENV !== 'production',
    playground: process.env.NODE_ENV !== 'production',
    installSubscriptionHandlers: true,
    autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
    // to allow guards on resolver props https://github.com/nestjs/graphql/issues/295
    fieldResolverEnhancers: [
      'guards',
      'interceptors',
    ],
    resolverValidationOptions: {

    },
    context: ({ req, connection }) => {
      if (!req && connection) {
        const headers: IncomingHttpHeaders = {}

        Object.keys(connection.context).forEach(key => {
          headers[key.toLowerCase()] = connection.context[key]
        })

        return {
          req: {
            headers,
          } as Request,
        }
      }

      return { req }
    },
  }),
  TypeOrmModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): TypeOrmModuleOptions => {
      const type: any = configService.get<string>('DATABASE_DRIVER', 'sqlite')
      let migrationFolder: string
      let migrationsTransactionMode: 'each' | 'none' | 'all' = 'each'

      switch (type) {
        case 'cockroachdb':
        case 'postgres':
          migrationFolder = 'postgres'
          break

        case 'mysql':
        case 'mariadb':
          migrationFolder = 'mariadb'
          break

        case 'sqlite':
          migrationFolder = 'sqlite'
          migrationsTransactionMode = 'none'
          break

        default:
          throw new Error('unsupported driver')
      }

      return ({
        name: 'ohmyform',
        synchronize: false,
        type,
        url: configService.get<string>('DATABASE_URL'),
        database: type === 'sqlite' ? configService.get<string>('DATABASE_URL', 'data.sqlite').replace('sqlite://', '') : undefined,
        ssl: configService.get<string>('DATABASE_SSL', 'false') === 'true' ? { rejectUnauthorized: false } : false,
        entityPrefix: configService.get<string>('DATABASE_TABLE_PREFIX', ''),
        logging: configService.get<string>('DATABASE_LOGGING', 'false') === 'true',
        entities,
        migrations: [`${__dirname}/**/migrations/${migrationFolder}/**/*{.ts,.js}`],
        migrationsRun: configService.get<boolean>('DATABASE_MIGRATE', true),
        migrationsTransactionMode,
      })
    },
  }),
  TypeOrmModule.forFeature(entities),
  MailerModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => ({
      transport: configService.get<string>('MAILER_URI', 'smtp://localhost:1025'),
      defaults: {
        from: configService.get<string>('MAILER_FROM', 'OhMyForm <no-reply@localhost>'),
      },
    }),
  }),
]
Example #20
Source File: app.module.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.local', '.env']
    }),
    SendGridModule.forRootAsync({
      imports: [ConfigModule, GoogleSecretsManagerModule],
      inject: [ConfigService, GoogleSecretsManagerService],
      useClass: SendgridConfigService
    }),
    ServeStaticModule.forRoot({
      rootPath: path.join(
        __dirname,
        '..',
        '..',
        '..',
        'amplication-client',
        'build'
      ),
      exclude: ['/graphql']
    }),

    RootWinstonModule,

    GraphQLModule.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        autoSchemaFile:
          configService.get('GRAPHQL_SCHEMA_DEST') || './src/schema.graphql',
        debug: configService.get('GRAPHQL_DEBUG') === '1',
        playground: configService.get('PLAYGROUND_ENABLE') === '1',
        context: ({ req }: { req: Request }) => ({
          req
        })
      }),
      inject: [ConfigService]
    }),

    RootStorageModule,

    MorganModule,
    SegmentAnalyticsModule.registerAsync({
      useClass: SegmentAnalyticsOptionsService
    }),
    CoreModule
  ],
  controllers: [],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: InjectContextInterceptor
    }
  ]
})
export class AppModule implements OnApplicationShutdown {
  onApplicationShutdown(signal: string) {
    console.trace(`Application shut down (signal: ${signal})`);
  }
}
Example #21
Source File: nestjs-integration-graphql.spec.ts    From nestjs-joi with MIT License 4 votes vote down vote up
describe('NestJS GraphQL integration', () => {
  @ObjectType()
  class Entity {
    @Field(() => ID)
    id!: string;

    @Field({})
    @JoiSchema(Joi.string().valid('default').required())
    @JoiSchema([JoiValidationGroups.CREATE], Joi.string().valid('create').required())
    @JoiSchema([JoiValidationGroups.UPDATE], Joi.string().valid('update').required())
    prop!: string;
  }

  @InputType()
  @JoiSchemaExtends(Entity)
  class CreateEntityInput extends OmitType(Entity, ['id'], InputType) {}

  @Resolver()
  class EntityResolver {
    @Query(() => Entity)
    entity(): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    create_ConstructorInArgs(@Args('input', JoiPipe) input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    create_InstanceInArgs(@Args('input', new JoiPipe()) input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    create_InstanceInArgsWithGroup(
      @Args('input', new JoiPipe({ group: CREATE })) input: CreateEntityInput,
    ): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    @UsePipes(JoiPipe)
    create_ConstructorInUsePipes(@Args('input') input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    @UsePipes(new JoiPipe())
    create_InstanceInUsePipes(@Args('input') input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    @UsePipes(new JoiPipe({ group: CREATE }))
    create_InstanceInUsePipesWithGroup(@Args('input') input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    @Mutation(() => Entity)
    create_NoPipe(@Args('input') input: CreateEntityInput): Entity {
      return this.getEntity();
    }

    private getEntity(): Entity {
      const entity = new Entity();
      entity.id = '1';
      entity.prop = 'newentity';

      return entity;
    }
  }

  let module: TestingModule;
  let app: INestApplication;

  describe('with pipes defined in resolver', () => {
    beforeEach(async () => {
      module = await Test.createTestingModule({
        imports: [
          GraphQLModule.forRoot({
            autoSchemaFile: true,
          }),
        ],
        providers: [EntityResolver],
      }).compile();

      app = module.createNestApplication();
      await app.init();
    });

    afterEach(async () => {
      await app.close();
    });

    const CASES = [
      {
        title: '@Args(JoiPipe)',
        mutation: 'create_ConstructorInArgs',
        propValue: 'default',
      },
      {
        title: '@Args(new JoiPipe)',
        mutation: 'create_InstanceInArgs',
        propValue: 'default',
      },
      {
        title: '@Args(new JoiPipe(CREATE))',
        mutation: 'create_InstanceInArgsWithGroup',
        propValue: 'create',
      },
      {
        title: '@UsePipes(JoiPipe)',
        mutation: 'create_ConstructorInUsePipes',
        propValue: 'default',
      },
      {
        title: '@UsePipes(new JoiPipe)',
        mutation: 'create_InstanceInUsePipes',
        propValue: 'default',
      },
      {
        title: '@UsePipes(new JoiPipe(CREATE))',
        mutation: 'create_InstanceInUsePipesWithGroup',
        propValue: 'create',
      },
    ];
    for (const { title, mutation, propValue } of CASES) {
      describe(title, () => {
        it('should use the pipe correctly (positive test)', async () => {
          return request(app.getHttpServer())
            .post('/graphql')
            .send({
              operationName: mutation,
              variables: {
                CreateEntityInput: {
                  prop: propValue,
                },
              },
              query: `
                mutation ${mutation}($CreateEntityInput: CreateEntityInput!) {
                  ${mutation}(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
            })
            .expect(res =>
              expect(res.body).toEqual({
                data: {
                  [mutation]: {
                    id: '1',
                    prop: 'newentity',
                  },
                },
              }),
            );
        });

        it('should use the pipe correctly (negative test)', async () => {
          return request(app.getHttpServer())
            .post('/graphql')
            .send({
              operationName: mutation,
              variables: {
                CreateEntityInput: {
                  prop: 'NOT' + propValue,
                },
              },
              query: `
                mutation ${mutation}($CreateEntityInput: CreateEntityInput!) {
                  ${mutation}(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
            })
            .expect(res =>
              expect(res.body.errors[0].message).toContain(`"prop" must be [${propValue}]`),
            );
        });
      });
    }
  });

  describe('with app.useGlobalPipes(new JoiPipe)', () => {
    beforeEach(async () => {
      module = await Test.createTestingModule({
        imports: [
          GraphQLModule.forRoot({
            autoSchemaFile: true,
          }),
        ],
        providers: [EntityResolver],
      }).compile();

      app = module.createNestApplication();
      app.useGlobalPipes(new JoiPipe());
      await app.init();
    });

    afterEach(async () => {
      await app.close();
    });

    it('should use the pipe correctly (positive test)', async () => {
      return request(app.getHttpServer())
        .post('/graphql')
        .send({
          operationName: 'create_NoPipe',
          variables: {
            CreateEntityInput: {
              prop: 'default',
            },
          },
          query: `
                mutation create_NoPipe($CreateEntityInput: CreateEntityInput!) {
                  create_NoPipe(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
        })
        .expect(res =>
          expect(res.body).toEqual({
            data: {
              create_NoPipe: {
                id: '1',
                prop: 'newentity',
              },
            },
          }),
        );
    });

    it('should use the pipe correctly (negative test)', async () => {
      return request(app.getHttpServer())
        .post('/graphql')
        .send({
          operationName: 'create_NoPipe',
          variables: {
            CreateEntityInput: {
              prop: 'NOT' + 'default',
            },
          },
          query: `
                mutation create_NoPipe($CreateEntityInput: CreateEntityInput!) {
                  create_NoPipe(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
        })
        .expect(res => expect(res.body.errors[0].message).toContain(`"prop" must be [default]`));
    });
  });

  describe('with app.useGlobalPipes(new JoiPipe(group))', () => {
    beforeEach(async () => {
      module = await Test.createTestingModule({
        imports: [
          GraphQLModule.forRoot({
            autoSchemaFile: true,
          }),
        ],
        providers: [EntityResolver],
      }).compile();

      app = module.createNestApplication();
      app.useGlobalPipes(new JoiPipe({ group: CREATE }));
      await app.init();
    });

    afterEach(async () => {
      await app.close();
    });

    it('should use the pipe correctly (positive test)', async () => {
      return request(app.getHttpServer())
        .post('/graphql')
        .send({
          operationName: 'create_NoPipe',
          variables: {
            CreateEntityInput: {
              prop: 'create',
            },
          },
          query: `
                mutation create_NoPipe($CreateEntityInput: CreateEntityInput!) {
                  create_NoPipe(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
        })
        .expect(res =>
          expect(res.body).toEqual({
            data: {
              create_NoPipe: {
                id: '1',
                prop: 'newentity',
              },
            },
          }),
        );
    });

    it('should use the pipe correctly (negative test)', async () => {
      return request(app.getHttpServer())
        .post('/graphql')
        .send({
          operationName: 'create_NoPipe',
          variables: {
            CreateEntityInput: {
              prop: 'NOT' + 'create',
            },
          },
          query: `
                mutation create_NoPipe($CreateEntityInput: CreateEntityInput!) {
                  create_NoPipe(input: $CreateEntityInput) {
                    id
                    prop
                  }
                }
              `,
        })
        .expect(res => expect(res.body.errors[0].message).toContain(`"prop" must be [create]`));
    });
  });
});
Example #22
Source File: build.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('BuildResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        BuildResolver,
        {
          provide: BuildService,
          useClass: jest.fn(() => ({
            findMany: buildServiceFindManyMock,
            findOne: buildServiceFindOneMock,
            calcBuildStatus: buildServiceCalcBuildStatusMock,
            getDeployments: buildServiceGetDeploymentsMock,
            create: buildServiceCreateMock
          }))
        },
        {
          provide: UserService,
          useClass: jest.fn(() => ({
            findUser: userServiceFindUserMock
          }))
        },
        {
          provide: ActionService,
          useClass: jest.fn(() => ({
            findOne: actionServiceFindOneMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should find many builds', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_BUILDS_QUERY,
      variables: {}
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      builds: [
        {
          ...EXAMPLE_BUILD,
          createdAt: EXAMPLE_BUILD.createdAt.toISOString()
        }
      ]
    });
    expect(buildServiceFindManyMock).toBeCalledTimes(1);
    expect(buildServiceFindManyMock).toBeCalledWith({});
  });

  it('should find one build', async () => {
    const res = await apolloClient.query({
      query: FIND_ONE_BUILD_QUERY,
      variables: { id: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        ...EXAMPLE_BUILD,
        createdAt: EXAMPLE_BUILD.createdAt.toISOString()
      }
    });
    expect(buildServiceFindOneMock).toBeCalledTimes(1);
    expect(buildServiceFindOneMock).toBeCalledWith({
      where: { id: EXAMPLE_BUILD_ID }
    });
  });

  it('should find a builds creating user', async () => {
    const res = await apolloClient.query({
      query: FIND_USER_QUERY,
      variables: { id: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        createdBy: {
          ...EXAMPLE_USER,
          createdAt: EXAMPLE_USER.createdAt.toISOString(),
          updatedAt: EXAMPLE_USER.updatedAt.toISOString(),
          isOwner: true
        }
      }
    });
    expect(userServiceFindUserMock).toBeCalledTimes(1);
    expect(userServiceFindUserMock).toBeCalledWith({
      where: { id: EXAMPLE_USER_ID }
    });
  });

  it('should find a builds action', async () => {
    const res = await apolloClient.query({
      query: FIND_ACTION_QUERY,
      variables: { id: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        action: {
          ...EXAMPLE_ACTION,
          createdAt: EXAMPLE_ACTION.createdAt.toISOString()
        }
      }
    });
    expect(actionServiceFindOneMock).toBeCalledTimes(1);
    expect(actionServiceFindOneMock).toBeCalledWith({
      where: { id: EXAMPLE_ACTION_ID }
    });
  });

  it('should return the build archive URI', async () => {
    const res = await apolloClient.query({
      query: ARCHIVE_URI_QUERY,
      variables: { id: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        archiveURI: `/generated-apps/${EXAMPLE_BUILD_ID}.zip`
      }
    });
  });

  it('should get a build status', async () => {
    const res = await apolloClient.query({
      query: BUILD_STATUS_QUERY,
      variables: { id: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        status: EnumBuildStatus.Completed
      }
    });
    expect(buildServiceCalcBuildStatusMock).toBeCalledTimes(1);
    expect(buildServiceCalcBuildStatusMock).toBeCalledWith(EXAMPLE_BUILD_ID);
  });

  it('should get a builds deployments', async () => {
    const res = await apolloClient.query({
      query: GET_DEPLOYMENTS_QUERY,
      variables: { buildId: EXAMPLE_BUILD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      build: {
        deployments: [
          {
            ...EXAMPLE_DEPLOYMENT,
            createdAt: EXAMPLE_DEPLOYMENT.createdAt.toISOString()
          }
        ]
      }
    });
    expect(buildServiceGetDeploymentsMock).toBeCalledTimes(1);
    expect(buildServiceGetDeploymentsMock).toBeCalledWith(EXAMPLE_BUILD_ID, {});
  });

  it('should create a build', async () => {
    const args = {
      data: {
        app: { connect: { id: EXAMPLE_APP_ID } },
        commit: { connect: { id: EXAMPLE_COMMIT_ID } },
        message: EXAMPLE_MESSAGE
      }
    };
    const res = await apolloClient.mutate({
      mutation: CREATE_BUILD_MUTATION,
      variables: {
        appId: EXAMPLE_APP_ID,
        commitId: EXAMPLE_COMMIT_ID,
        message: EXAMPLE_MESSAGE
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createBuild: {
        ...EXAMPLE_BUILD,
        createdAt: EXAMPLE_BUILD.createdAt.toISOString()
      }
    });
    expect(buildServiceCreateMock).toBeCalledTimes(1);
    expect(buildServiceCreateMock).toBeCalledWith(args);
  });
});
Example #23
Source File: web.module.ts    From relate with GNU General Public License v3.0 4 votes vote down vote up
@Module({
    imports: [
        SystemModule,
        DBMSModule,
        DBMSPluginsModule,
        DBModule,
        ExtensionModule,
        ProjectModule,
        FilesModule,
        GraphQLModule.forRootAsync({
            useFactory: (configService: ConfigService<IWebModuleConfig>, systemProvider: SystemProvider) => ({
                playground: {
                    settings: {
                        'request.credentials': 'same-origin',
                    },
                },
                autoSchemaFile: configService.get('autoSchemaFile'),
                subscriptions: {
                    // @todo - This is temporarily enabled in development
                    // because graphql playground and apollo explorer don't yet
                    // support `graphql-ws`. It shouldn't be enabled in
                    // production because `subscriptions-transport-ws` has a bug
                    // that will allow certain connections to skip the
                    // onConnection handler, bypassing the token check.
                    'subscriptions-transport-ws':
                        process.env.NODE_ENV === 'development' ? subscriptionsTransportWs(systemProvider) : false,
                    'graphql-ws': graphqlWs(systemProvider),
                },
            }),
            imports: [SystemModule],
            inject: [ConfigService, SystemProvider],
        }),
        HealthModule,
        AuthModule,
    ],
})
export class WebModule implements OnModuleInit {
    static register(config: IWebModuleConfig): DynamicModule {
        const {defaultEnvironmentNameOrId} = config;
        const webExtensions = loadExtensionsFor(EXTENSION_TYPES.WEB, defaultEnvironmentNameOrId);

        return {
            imports: [SystemModule.register(config), ...webExtensions],
            module: WebModule,
            exports: [SystemModule, ...webExtensions],
        };
    }

    constructor(
        @Inject(GraphQLSchemaHost) private readonly schemaHost: GraphQLSchemaHost,
        @Inject(HttpAdapterHost) private readonly httpAdapterHost: HttpAdapterHost,
    ) {}

    onModuleInit(): void {
        if (!this.httpAdapterHost) {
            return;
        }

        const {httpAdapter} = this.httpAdapterHost;
        const app: Application = httpAdapter.getInstance();
        const {schema} = this.schemaHost;
        const openApi = OpenAPI({
            schema,
            info: {
                title: 'Relate REST API',
                version: '1.0.0',
            },
        });

        // add multer to file upload endpoints
        const uploads = multer({dest: envPaths().tmp});

        app.use('/api/add-project-file', uploads.single('fileUpload'), (req, _, next) => {
            req.body = {
                ...req.body,
                fileUpload: {
                    // convert multer file object to the same shape as graphql-upload
                    ...req.file,
                    filename: req.file.originalname,
                },
            };
            next();
        });

        // convert GraphQL API to REST using SOFA
        app.use(
            '/api',
            useSofa({
                basePath: '/api',
                schema,
                onRoute(info) {
                    openApi.addRoute(info, {
                        basePath: '/api',
                    });
                },
            }),
        );

        // add Swagger page for REST API
        const openApiDefinitions = openApi.get();
        openApiDefinitions.paths['/api/add-project-file'] = fixAddProjectFilesOpenAPIDef(
            openApiDefinitions.paths['/api/add-project-file'],
        );

        app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openApiDefinitions));
    }
}
Example #24
Source File: account.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('AccountResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        AccountResolver,
        {
          provide: AccountService,
          useClass: jest.fn(() => ({
            updateAccount: updateAccountMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: PrismaService,
          useClass: jest.fn(() => ({}))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should get current account', async () => {
    const res = await apolloClient.query({
      query: GET_ACCOUNT_QUERY
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      account: {
        id: EXAMPLE_ACCOUNT.id,
        createdAt: EXAMPLE_ACCOUNT.createdAt.toISOString(),
        updatedAt: EXAMPLE_ACCOUNT.updatedAt.toISOString(),
        email: EXAMPLE_ACCOUNT.email,
        firstName: EXAMPLE_ACCOUNT.firstName,
        lastName: EXAMPLE_ACCOUNT.lastName,
        password: EXAMPLE_ACCOUNT.password
      }
    });
  });

  it('should update an account', async () => {
    const variables = {
      data: {
        firstName: EXAMPLE_UPDATED_ACCOUNT.firstName,
        lastName: EXAMPLE_UPDATED_ACCOUNT.lastName
      }
    };
    const res = await apolloClient.query({
      query: UPDATE_ACCOUNT_MUTATION,
      variables
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateAccount: {
        ...EXAMPLE_UPDATED_ACCOUNT,
        createdAt: EXAMPLE_ACCOUNT.createdAt.toISOString(),
        updatedAt: EXAMPLE_ACCOUNT.updatedAt.toISOString()
      }
    });
    expect(updateAccountMock).toBeCalledTimes(1);
    expect(updateAccountMock).toBeCalledWith({
      where: { id: EXAMPLE_ACCOUNT_ID },
      data: variables.data
    });
  });
});
Example #25
Source File: app.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('AppResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        AppResolver,
        {
          provide: AppService,
          useClass: jest.fn(() => ({
            app: appMock,
            createApp: createAppMock,
            deleteApp: deleteAppMock,
            updateApp: updateAppMock,
            commit: commitMock,
            discardPendingChanges: discardPendingChangesMock,
            getPendingChanges: getPendingChangesMock
          }))
        },
        {
          provide: UserService,
          useClass: jest.fn(() => ({
            findUser: userServiceFindUserMock
          }))
        },
        {
          provide: EntityService,
          useClass: jest.fn(() => ({
            entities: entitiesMock
          }))
        },
        {
          provide: BuildService,
          useClass: jest.fn(() => ({
            findMany: findManyBuildMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: EnvironmentService,
          useClass: jest.fn(() => ({
            findMany: findManyEnvironmentsMock
          }))
        },
        {
          provide: PrismaService,
          useClass: jest.fn(() => ({}))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should find one app', async () => {
    const res = await apolloClient.query({
      query: FIND_ONE_APP_QUERY,
      variables: { id: EXAMPLE_APP_ID }
    });
    const args = { where: { id: EXAMPLE_APP_ID } };
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      app: {
        ...EXAMPLE_APP,
        createdAt: EXAMPLE_APP.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP.updatedAt.toISOString(),
        entities: [
          {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        ],
        builds: [
          {
            ...EXAMPLE_BUILD,
            createdAt: EXAMPLE_BUILD.createdAt.toISOString()
          }
        ],
        environments: [
          {
            ...EXAMPLE_ENVIRONMENT,
            createdAt: EXAMPLE_ENVIRONMENT.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENVIRONMENT.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(appMock).toBeCalledTimes(1);
    expect(appMock).toBeCalledWith(args);
  });

  it('should find many entities', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_ENTITIES_QUERY,
      variables: { appId: EXAMPLE_APP_ID, entityId: EXAMPLE_ENTITY_ID }
    });
    const args = {
      where: { id: { equals: EXAMPLE_ENTITY_ID }, app: { id: EXAMPLE_APP_ID } }
    };
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      app: {
        entities: [
          {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(entitiesMock).toBeCalledTimes(1);
    expect(entitiesMock).toBeCalledWith(args);
  });

  it('should find many builds', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_BUILDS_QUERY,
      variables: { appId: EXAMPLE_APP_ID }
    });
    const args = {
      where: { app: { id: EXAMPLE_APP_ID } }
    };
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      app: {
        builds: [
          {
            ...EXAMPLE_BUILD,
            createdAt: EXAMPLE_BUILD.createdAt.toISOString()
          }
        ]
      }
    });
    expect(findManyBuildMock).toBeCalledTimes(1);
    expect(findManyBuildMock).toBeCalledWith(args);
  });

  it('should find many environments', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_ENVIRONMENTS_QUERY,
      variables: { appId: EXAMPLE_APP_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      app: {
        environments: [
          {
            ...EXAMPLE_ENVIRONMENT,
            createdAt: EXAMPLE_ENVIRONMENT.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENVIRONMENT.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(findManyEnvironmentsMock).toBeCalledTimes(1);
    expect(findManyEnvironmentsMock).toBeCalledWith({
      where: { app: { id: EXAMPLE_APP_ID } }
    });
  });

  it('should create an app', async () => {
    const res = await apolloClient.query({
      query: CREATE_APP_MUTATION,
      variables: {
        name: EXAMPLE_NAME,
        description: EXAMPLE_DESCRIPTION
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createApp: {
        ...EXAMPLE_APP,
        createdAt: EXAMPLE_APP.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP.updatedAt.toISOString(),
        entities: [
          {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        ],
        builds: [
          {
            ...EXAMPLE_BUILD,
            createdAt: EXAMPLE_BUILD.createdAt.toISOString()
          }
        ],
        environments: [
          {
            ...EXAMPLE_ENVIRONMENT,
            createdAt: EXAMPLE_ENVIRONMENT.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENVIRONMENT.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(createAppMock).toBeCalledTimes(1);
    expect(createAppMock).toBeCalledWith(
      {
        data: {
          name: EXAMPLE_NAME,
          description: EXAMPLE_DESCRIPTION
        }
      },
      EXAMPLE_USER
    );
  });

  it('should delete an app', async () => {
    const res = await apolloClient.query({
      query: DELETE_APP_MUTATION,
      variables: {
        id: EXAMPLE_APP_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteApp: {
        ...EXAMPLE_APP,
        createdAt: EXAMPLE_APP.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP.updatedAt.toISOString(),
        entities: [
          {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        ],
        builds: [
          {
            ...EXAMPLE_BUILD,
            createdAt: EXAMPLE_BUILD.createdAt.toISOString()
          }
        ],
        environments: [
          {
            ...EXAMPLE_ENVIRONMENT,
            createdAt: EXAMPLE_ENVIRONMENT.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENVIRONMENT.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(deleteAppMock).toBeCalledTimes(1);
    expect(deleteAppMock).toBeCalledWith({ where: { id: EXAMPLE_APP_ID } });
  });

  it('should update an app', async () => {
    const res = await apolloClient.query({
      query: UPDATE_APP_MUTATION,
      variables: {
        name: EXAMPLE_NAME,
        id: EXAMPLE_APP_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateApp: {
        ...EXAMPLE_APP,
        createdAt: EXAMPLE_APP.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP.updatedAt.toISOString(),
        entities: [
          {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        ],
        builds: [
          {
            ...EXAMPLE_BUILD,
            createdAt: EXAMPLE_BUILD.createdAt.toISOString()
          }
        ],
        environments: [
          {
            ...EXAMPLE_ENVIRONMENT,
            createdAt: EXAMPLE_ENVIRONMENT.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENVIRONMENT.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(updateAppMock).toBeCalledTimes(1);
    expect(updateAppMock).toBeCalledWith({
      data: { name: EXAMPLE_NAME },
      where: { id: EXAMPLE_APP_ID }
    });
  });

  it('should commit', async () => {
    const res = await apolloClient.query({
      query: COMMIT_MUTATION,
      variables: { message: EXAMPLE_MESSAGE, appId: EXAMPLE_APP_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      commit: {
        ...EXAMPLE_COMMIT,
        createdAt: EXAMPLE_COMMIT.createdAt.toISOString()
      }
    });
    expect(commitMock).toBeCalledTimes(1);
    expect(commitMock).toBeCalledWith({
      data: {
        message: EXAMPLE_MESSAGE,
        app: { connect: { id: EXAMPLE_APP_ID } }
      }
    });
  });

  it('should discard pending changes', async () => {
    const res = await apolloClient.query({
      query: DISCARD_CHANGES_MUTATION,
      variables: { appId: EXAMPLE_APP_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      discardPendingChanges: true
    });
    expect(discardPendingChangesMock).toBeCalledTimes(1);
    expect(discardPendingChangesMock).toBeCalledWith({
      data: { app: { connect: { id: EXAMPLE_APP_ID } } }
    });
  });

  it('should get a pending change', async () => {
    const res = await apolloClient.query({
      query: PENDING_CHANGE_QUERY,
      variables: { appId: EXAMPLE_APP_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      pendingChanges: [
        {
          ...EXAMPLE_PENDING_CHANGE,
          resource: {
            ...EXAMPLE_ENTITY,
            createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
          }
        }
      ]
    });
    expect(getPendingChangesMock).toBeCalledTimes(1);
    expect(getPendingChangesMock).toBeCalledWith(
      {
        where: { app: { id: EXAMPLE_APP_ID } }
      },
      EXAMPLE_USER
    );
  });
});
Example #26
Source File: appRole.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('AppRoleResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        AppRoleResolver,
        {
          provide: AppRoleService,
          useClass: jest.fn(() => ({
            getAppRole: getAppRoleMock,
            getAppRoles: getAppRolesMock,
            createAppRole: createAppRoleMock,
            deleteAppRole: deleteAppRoleMock,
            updateAppRole: updateAppRoleMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },

        {
          provide: PrismaService,
          useClass: jest.fn(() => ({}))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should get one AppRole', async () => {
    const res = await apolloClient.query({
      query: GET_APP_ROLE_QUERY,
      variables: { id: EXAMPLE_APP_ROLE_ID, version: EXAMPLE_VERSION }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      appRole: {
        ...EXAMPLE_APP_ROLE,
        createdAt: EXAMPLE_APP_ROLE.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP_ROLE.updatedAt.toISOString()
      }
    });
    expect(getAppRoleMock).toBeCalledTimes(1);
    expect(getAppRoleMock).toBeCalledWith({
      where: { id: EXAMPLE_APP_ROLE_ID },
      version: EXAMPLE_VERSION
    });
  });

  it('should get Many AppRoles', async () => {
    const res = await apolloClient.query({
      query: GET_APP_ROLES_QUERY
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      appRoles: [
        {
          ...EXAMPLE_APP_ROLE,
          createdAt: EXAMPLE_APP_ROLE.createdAt.toISOString(),
          updatedAt: EXAMPLE_APP_ROLE.updatedAt.toISOString()
        }
      ]
    });
    expect(getAppRolesMock).toBeCalledTimes(1);
    expect(getAppRolesMock).toBeCalledWith({});
  });

  it('should create an AppRole', async () => {
    const res = await apolloClient.query({
      query: CREATE_APP_ROLE_MUTATION,
      variables: {
        name: EXAMPLE_NAME,
        description: EXAMPLE_DESCRIPTION,
        displayName: EXAMPLE_DISPLAY_NAME,
        appId: EXAMPLE_APP_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createAppRole: {
        ...EXAMPLE_APP_ROLE,
        createdAt: EXAMPLE_APP_ROLE.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP_ROLE.updatedAt.toISOString()
      }
    });
    expect(createAppRoleMock).toBeCalledTimes(1);
    expect(createAppRoleMock).toBeCalledWith({
      data: {
        name: EXAMPLE_NAME,
        description: EXAMPLE_DESCRIPTION,
        displayName: EXAMPLE_DISPLAY_NAME,
        app: { connect: { id: EXAMPLE_APP_ID } }
      }
    });
  });

  it('should delete an AppRole', async () => {
    const res = await apolloClient.query({
      query: DELETE_APP_ROLE_MUTATION,
      variables: { id: EXAMPLE_APP_ROLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteAppRole: {
        ...EXAMPLE_APP_ROLE,
        createdAt: EXAMPLE_APP_ROLE.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP_ROLE.updatedAt.toISOString()
      }
    });
    expect(deleteAppRoleMock).toBeCalledTimes(1);
    expect(deleteAppRoleMock).toBeCalledWith({
      where: { id: EXAMPLE_APP_ROLE_ID }
    });
  });

  it('should update an AppRole', async () => {
    const res = await apolloClient.query({
      query: UPDATE_APP_ROLE_MUTATION,
      variables: { id: EXAMPLE_APP_ROLE_ID, displayName: EXAMPLE_DISPLAY_NAME }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateAppRole: {
        ...EXAMPLE_APP_ROLE,
        createdAt: EXAMPLE_APP_ROLE.createdAt.toISOString(),
        updatedAt: EXAMPLE_APP_ROLE.updatedAt.toISOString()
      }
    });
    expect(updateAppRoleMock).toBeCalledTimes(1);
    expect(updateAppRoleMock).toBeCalledWith({
      where: { id: EXAMPLE_APP_ROLE_ID },
      data: { displayName: EXAMPLE_DISPLAY_NAME }
    });
  });
});
Example #27
Source File: auth.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('AuthResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        AuthResolver,
        {
          provide: AuthService,
          useClass: jest.fn(() => ({
            signup: authServiceSignUpMock,
            login: authServiceLoginMock,
            changePassword: authServiceChangePasswordMock,
            setCurrentWorkspace: setCurrentWorkspaceMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should return current user', async () => {
    const res = await apolloClient.query({
      query: ME_QUERY
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      me: {
        id: EXAMPLE_USER.id,
        createdAt: EXAMPLE_USER.createdAt.toISOString(),
        updatedAt: EXAMPLE_USER.updatedAt.toISOString()
      }
    });
  });

  it('should signup', async () => {
    const variables = {
      email: EXAMPLE_EMAIL,
      password: EXAMPLE_PASSWORD,
      firstName: EXAMPLE_FIRST_NAME,
      lastName: EXAMPLE_LAST_NAME,
      workspaceName: EXAMPLE_WORKSPACE_NAME
    };
    const res = await apolloClient.mutate({
      mutation: SIGNUP_MUTATION,
      variables: variables
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      signup: {
        ...EXAMPLE_AUTH
      }
    });
    expect(authServiceSignUpMock).toBeCalledTimes(1);
    expect(authServiceSignUpMock).toBeCalledWith({
      ...variables,
      email: variables.email.toLowerCase()
    });
  });

  it('should login', async () => {
    const variables = {
      email: EXAMPLE_EMAIL,
      password: EXAMPLE_PASSWORD
    };
    const res = await apolloClient.mutate({
      mutation: LOGIN_MUTATION,
      variables: variables
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      login: {
        ...EXAMPLE_AUTH
      }
    });
    expect(authServiceLoginMock).toBeCalledTimes(1);
    expect(authServiceLoginMock).toBeCalledWith(
      EXAMPLE_EMAIL.toLowerCase(),
      EXAMPLE_PASSWORD
    );
  });

  it('should change a password', async () => {
    const res = await apolloClient.mutate({
      mutation: CHANGE_PASSWORD_MUTATION,
      variables: {
        oldPassword: EXAMPLE_PASSWORD,
        newPassword: EXAMPLE_PASSWORD
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      changePassword: {
        ...EXAMPLE_ACCOUNT,
        createdAt: EXAMPLE_ACCOUNT.createdAt.toISOString(),
        updatedAt: EXAMPLE_ACCOUNT.updatedAt.toISOString()
      }
    });
    expect(authServiceChangePasswordMock).toBeCalledTimes(1);
    expect(authServiceChangePasswordMock).toBeCalledWith(
      EXAMPLE_USER.account,
      EXAMPLE_PASSWORD,
      EXAMPLE_PASSWORD
    );
  });

  it('set set the current workspace', async () => {
    const res = await apolloClient.mutate({
      mutation: SET_WORKSPACE_MUTATION,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      setCurrentWorkspace: {
        ...EXAMPLE_AUTH
      }
    });
    expect(setCurrentWorkspaceMock).toBeCalledTimes(1);
    expect(setCurrentWorkspaceMock).toBeCalledWith(
      EXAMPLE_ACCOUNT_ID,
      EXAMPLE_WORKSPACE_ID
    );
  });

  it('should throw error if user has no account', async () => {
    mockCanActivate.mockImplementation(
      mockGqlAuthGuardCanActivate(EXAMPLE_USER_WITHOUT_ACCOUNT)
    );
    const { data, errors } = await apolloClient.mutate({
      mutation: SET_WORKSPACE_MUTATION,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });

    expect(data).toEqual(null); //make sure no data is forward
    expect(errors.length === 1); // make sure only one error is send
    const error = errors[0];
    expect(error.message === 'User has no account'); // make sure the error message is valid
    expect(setCurrentWorkspaceMock).toBeCalledTimes(0);
  });
});
Example #28
Source File: workspace.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('WorkspaceResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        WorkspaceResolver,
        {
          provide: WorkspaceService,
          useClass: jest.fn(() => ({
            getWorkspace: workspaceServiceGetWorkspaceMock,
            deleteWorkspace: workspaceServiceDeleteWorkspaceMock,
            updateWorkspace: workspaceServiceUpdateWorkspaceMock,
            inviteUser: workspaceServiceInviteUserMock
          }))
        },
        {
          provide: AppService,
          useClass: jest.fn(() => ({
            apps: appServiceAppsMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should get an workspace', async () => {
    const res = await apolloClient.query({
      query: GET_WORKSPACE_QUERY,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      workspace: {
        ...EXAMPLE_WORKSPACE,
        createdAt: EXAMPLE_WORKSPACE.createdAt.toISOString(),
        updatedAt: EXAMPLE_WORKSPACE.updatedAt.toISOString()
      }
    });
    expect(workspaceServiceGetWorkspaceMock).toBeCalledTimes(1);
    expect(workspaceServiceGetWorkspaceMock).toBeCalledWith({
      where: { id: EXAMPLE_WORKSPACE_ID }
    });
  });

  it('should get an workspace apps', async () => {
    const res = await apolloClient.query({
      query: GET_APPS_QUERY,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      workspace: {
        apps: [
          {
            ...EXAMPLE_APP,
            createdAt: EXAMPLE_APP.createdAt.toISOString(),
            updatedAt: EXAMPLE_APP.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(appServiceAppsMock).toBeCalledTimes(1);
    expect(appServiceAppsMock).toBeCalledWith({
      where: { workspace: { id: EXAMPLE_WORKSPACE_ID } }
    });
  });

  it('should delete an workspace', async () => {
    const res = await apolloClient.mutate({
      mutation: DELETE_WORKSPACE_MUTATION,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteWorkspace: {
        ...EXAMPLE_WORKSPACE,
        createdAt: EXAMPLE_WORKSPACE.createdAt.toISOString(),
        updatedAt: EXAMPLE_WORKSPACE.updatedAt.toISOString()
      }
    });
    expect(workspaceServiceDeleteWorkspaceMock).toBeCalledTimes(1);
    expect(workspaceServiceDeleteWorkspaceMock).toBeCalledWith({
      where: { id: EXAMPLE_WORKSPACE_ID }
    });
  });

  it('should update an workspace', async () => {
    const res = await apolloClient.mutate({
      mutation: UPDATE_WORKSPACE_MUTATION,
      variables: { id: EXAMPLE_WORKSPACE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateWorkspace: {
        ...EXAMPLE_WORKSPACE,
        createdAt: EXAMPLE_WORKSPACE.createdAt.toISOString(),
        updatedAt: EXAMPLE_WORKSPACE.updatedAt.toISOString()
      }
    });
    expect(workspaceServiceUpdateWorkspaceMock).toBeCalledTimes(1);
    expect(workspaceServiceUpdateWorkspaceMock).toBeCalledWith({
      data: {},
      where: { id: EXAMPLE_WORKSPACE_ID }
    });
  });

  it('should invite a user', async () => {
    const res = await apolloClient.mutate({
      mutation: INVITE_USER_MUTATION,
      variables: { email: EXAMPLE_EMAIL }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      inviteUser: {
        ...EXAMPLE_INVITATION,
        createdAt: EXAMPLE_USER.createdAt.toISOString(),
        updatedAt: EXAMPLE_USER.updatedAt.toISOString()
      }
    });
    expect(workspaceServiceInviteUserMock).toBeCalledTimes(1);
    expect(workspaceServiceInviteUserMock).toBeCalledWith(EXAMPLE_USER, {
      data: { email: EXAMPLE_EMAIL }
    });
  });
});
Example #29
Source File: entity.resolver.spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe('EntityResolver', () => {
  let app: INestApplication;
  let apolloClient: ApolloServerTestClient;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      providers: [
        EntityResolver,
        EntityVersionResolver,
        {
          provide: EntityService,
          useClass: jest.fn(() => ({
            entity: entityMock,
            entities: entitiesMock,
            createOneEntity: entityCreateOneMock,
            getFields: getEntityFieldsMock,
            getPermissions: getPermissionsMock,
            getVersions: getVersionsMock,
            acquireLock: acquireLockMock,
            updateOneEntity: updateOneEntityMock,
            deleteOneEntity: deleteOneEntityMock,
            updateEntityPermission: updateEntityPermissionMock,
            updateEntityPermissionRoles: updateEntityPermissionRolesMock,
            addEntityPermissionField: addEntityPermissionFieldMock,
            deleteEntityPermissionField: deleteEntityPermissionFieldMock,
            updateEntityPermissionFieldRoles: updateEntityPermissionFieldRolesMock,
            createField: createFieldMock,
            createFieldByDisplayName: createFieldByDisplayNameMock,
            deleteField: deleteFieldMock,
            updateField: updateFieldMock,
            createDefaultRelatedField: createDefaultRelatedFieldMock,
            getVersion: entityServiceGetVersionMock,
            getVersionCommit: entityServiceGetVersionCommitMock,
            getVersionFields: entityServiceGetVersionFieldsMock,
            getVersionPermissions: entityServiceGetVersionPermissionsMock
          }))
        },
        {
          provide: UserService,
          useClass: jest.fn(() => ({
            findUser: findUserMock
          }))
        },
        {
          provide: WINSTON_MODULE_PROVIDER,
          useClass: jest.fn(() => ({
            error: jest.fn()
          }))
        },
        {
          provide: ConfigService,
          useClass: jest.fn(() => ({
            get: jest.fn()
          }))
        }
      ],
      imports: [GraphQLModule.forRoot({ autoSchemaFile: true })]
    })
      .overrideGuard(GqlAuthGuard)
      .useValue({ canActivate: mockCanActivate })
      .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const graphqlModule = moduleFixture.get(GraphQLModule) as any;
    apolloClient = createTestClient(graphqlModule.apolloServer);
  });

  it('should find one entity', async () => {
    const res = await apolloClient.query({
      query: FIND_ONE_QUERY,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        ...EXAMPLE_ENTITY,
        createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
      }
    });
    expect(entityMock).toBeCalledTimes(1);
    expect(entityMock).toBeCalledWith({ where: { id: EXAMPLE_ID } });
  });

  it('should find many entities', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_QUERY,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entities: [
        {
          ...EXAMPLE_ENTITY,
          createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
          updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
        }
      ]
    });
    expect(entitiesMock).toBeCalledTimes(1);
    expect(entitiesMock).toBeCalledWith({
      where: { id: { equals: EXAMPLE_ID } }
    });
  });

  it('should create one entity', async () => {
    const res = await apolloClient.query({
      query: CREATE_ONE_QUERY,
      variables: {
        name: EXAMPLE_ENTITY.name,
        displayName: EXAMPLE_ENTITY.displayName,
        pluralDisplayName: EXAMPLE_ENTITY.pluralDisplayName,
        id: EXAMPLE_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createOneEntity: {
        ...EXAMPLE_ENTITY,
        createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
      }
    });
    expect(entityCreateOneMock).toBeCalledTimes(1);
    expect(entityCreateOneMock).toBeCalledWith(
      {
        data: {
          name: EXAMPLE_ENTITY.name,
          displayName: EXAMPLE_ENTITY.displayName,
          pluralDisplayName: EXAMPLE_ENTITY.pluralDisplayName,
          app: { connect: { id: EXAMPLE_ID } }
        }
      },
      EXAMPLE_USER
    );
  });

  it('should get entity fields', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_FIELDS_QUERY,
      variables: { entityId: EXAMPLE_ID, fieldId: EXAMPLE_ENTITY_FIELD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        fields: [
          {
            ...EXAMPLE_ENTITY_FIELD,
            createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
            updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
          }
        ]
      }
    });
    expect(getEntityFieldsMock).toBeCalledTimes(1);
    expect(getEntityFieldsMock).toBeCalledWith(EXAMPLE_ID, {
      where: { id: { equals: EXAMPLE_ENTITY_FIELD_ID } }
    });
  });

  it('should get entity permissions', async () => {
    const res = await apolloClient.query({
      query: FIND_MANY_PERMISSIONS_QUERY,
      variables: { entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        permissions: [
          {
            ...EXAMPLE_PERMISSION
          }
        ]
      }
    });
    expect(getPermissionsMock).toBeCalledTimes(1);
    expect(getPermissionsMock).toBeCalledWith(EXAMPLE_ID);
  });

  it('should return locking user', async () => {
    const res = await apolloClient.query({
      query: LOCKED_BY_USER_QUERY,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        lockedByUser: {
          ...EXAMPLE_USER,
          createdAt: EXAMPLE_USER.createdAt.toISOString(),
          updatedAt: EXAMPLE_USER.updatedAt.toISOString(),
          isOwner: true
        }
      }
    });
    expect(findUserMock).toBeCalledTimes(1);
    expect(findUserMock).toBeCalledWith({ where: { id: EXAMPLE_USER_ID } });
  });

  it('should return null when no locking user', async () => {
    entityMock.mockImplementationOnce(() => EXAMPLE_UNLOCKED_ENTITY);

    const res = await apolloClient.query({
      query: LOCKED_BY_USER_QUERY,
      variables: { id: EXAMPLE_UNLOCKED_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        lockedByUser: null
      }
    });
    expect(findUserMock).toBeCalledTimes(0);
  });

  it('should lock an entity', async () => {
    const res = await apolloClient.query({
      query: LOCK_ENTITY_MUTATION,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      lockEntity: {
        ...EXAMPLE_ENTITY,
        createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
      }
    });
    expect(acquireLockMock).toBeCalledTimes(1);
    expect(acquireLockMock).toBeCalledWith(
      { where: { id: EXAMPLE_ID } },
      EXAMPLE_USER
    );
  });

  it('should update one entity', async () => {
    const res = await apolloClient.query({
      query: UPDATE_ENTITY_MUTATION,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateEntity: {
        ...EXAMPLE_ENTITY,
        createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
      }
    });
    expect(updateOneEntityMock).toBeCalledTimes(1);
    expect(updateOneEntityMock).toBeCalledWith(
      {
        data: {},
        where: { id: EXAMPLE_ID }
      },
      EXAMPLE_USER
    );
  });

  it('should delete one entity', async () => {
    const res = await apolloClient.query({
      query: DELETE_ENTITY_MUTATION,
      variables: { id: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteEntity: {
        ...EXAMPLE_ENTITY,
        createdAt: EXAMPLE_ENTITY.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY.updatedAt.toISOString()
      }
    });
    expect(deleteOneEntityMock).toBeCalledTimes(1);
    expect(deleteOneEntityMock).toBeCalledWith(
      { where: { id: EXAMPLE_ID } },
      EXAMPLE_USER
    );
  });

  it('should update an entity permission', async () => {
    const res = await apolloClient.query({
      query: UPDATE_ENTITY_PERM_MUTATUION,
      variables: {
        action: EXAMPLE_PERMISSION.action,
        type: EXAMPLE_PERMISSION.type,
        id: EXAMPLE_PERMISSION_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateEntityPermission: {
        ...EXAMPLE_PERMISSION
      }
    });
    expect(updateEntityPermissionMock).toBeCalledTimes(1);
    expect(updateEntityPermissionMock).toBeCalledWith(
      {
        data: {
          action: EXAMPLE_PERMISSION.action,
          type: EXAMPLE_PERMISSION.type
        },
        where: { id: EXAMPLE_PERMISSION_ID }
      },
      EXAMPLE_USER
    );
  });

  it('should update entity permission roles', async () => {
    const res = await apolloClient.query({
      query: UPDATE_ENTITY_PERM_ROLES_MUTATION,
      variables: { action: EXAMPLE_PERMISSION.action, entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateEntityPermissionRoles: {
        ...EXAMPLE_PERMISSION
      }
    });
    expect(updateEntityPermissionRolesMock).toBeCalledTimes(1);
    expect(updateEntityPermissionRolesMock).toBeCalledWith(
      {
        data: {
          action: EXAMPLE_PERMISSION.action,
          entity: { connect: { id: EXAMPLE_ID } }
        }
      },
      EXAMPLE_USER
    );
  });

  it('should add an entity permission field', async () => {
    const res = await apolloClient.query({
      query: ADD_ENTITY_PERM_FIELD_MUTATION,
      variables: {
        action: EXAMPLE_PERMISSION.action,
        fieldName: EXAMPLE_NAME,
        entityId: EXAMPLE_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      addEntityPermissionField: {
        ...EXAMPLE_PERMISSION_FIELD,
        field: {
          ...EXAMPLE_ENTITY_FIELD,
          createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
          updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
        }
      }
    });
    expect(addEntityPermissionFieldMock).toBeCalledTimes(1);
    expect(addEntityPermissionFieldMock).toBeCalledWith(
      {
        data: {
          action: EXAMPLE_PERMISSION.action,
          fieldName: EXAMPLE_NAME,
          entity: { connect: { id: EXAMPLE_ID } }
        }
      },
      EXAMPLE_USER
    );
  });

  it('should delete an entity permission field', async () => {
    const res = await apolloClient.query({
      query: DELETE_ENTITY_PERM_FIELD_MUTATION,
      variables: {
        action: EXAMPLE_PERMISSION.action,
        fieldPermanentId: EXAMPLE_FIELD_PERMANENT_ID,
        entityId: EXAMPLE_ID
      }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteEntityPermissionField: {
        ...EXAMPLE_PERMISSION_FIELD,
        field: {
          ...EXAMPLE_ENTITY_FIELD,
          createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
          updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
        }
      }
    });
    expect(deleteEntityPermissionFieldMock).toBeCalledTimes(1);
    expect(deleteEntityPermissionFieldMock).toBeCalledWith(
      {
        where: {
          action: EXAMPLE_PERMISSION.action,
          fieldPermanentId: EXAMPLE_FIELD_PERMANENT_ID,
          entityId: EXAMPLE_ID
        }
      },
      EXAMPLE_USER
    );
  });

  it('should update entity permission field roles', async () => {
    const res = await apolloClient.query({
      query: UPDATE_ENTITY_PERM_FIELD_ROLES_MUTATION,
      variables: { permissionFieldId: EXAMPLE_PERMISSION_FIELD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateEntityPermissionFieldRoles: {
        ...EXAMPLE_PERMISSION_FIELD,
        field: {
          ...EXAMPLE_ENTITY_FIELD,
          createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
          updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
        }
      }
    });
    expect(updateEntityPermissionFieldRolesMock).toBeCalledTimes(1);
    expect(updateEntityPermissionFieldRolesMock).toBeCalledWith(
      {
        data: {
          permissionField: { connect: { id: EXAMPLE_PERMISSION_FIELD_ID } }
        }
      },
      EXAMPLE_USER
    );
  });

  it('should create an entity field', async () => {
    const variables = {
      name: EXAMPLE_NAME,
      displayName: EXAMPLE_DISPLAY_NAME,
      dataType: EXAMPLE_ENTITY_FIELD.dataType,
      properties: EXAMPLE_ENTITY_FIELD.properties,
      required: EXAMPLE_ENTITY_FIELD.required,
      unique: EXAMPLE_ENTITY_FIELD.unique,
      searchable: EXAMPLE_ENTITY_FIELD.searchable,
      description: EXAMPLE_ENTITY_FIELD.description,
      entity: EXAMPLE_ID
    };
    const res = await apolloClient.query({
      query: CREATE_ENTITY_FIELD_MUTATION,
      variables: variables
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createEntityField: {
        ...EXAMPLE_ENTITY_FIELD,
        createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
      }
    });
    expect(createFieldMock).toBeCalledTimes(1);
    expect(createFieldMock).toBeCalledWith(
      { data: { ...variables, entity: { connect: { id: EXAMPLE_ID } } } },
      EXAMPLE_USER
    );
  });

  it('should create entity field by display name', async () => {
    const res = await apolloClient.query({
      query: CREATE_ENTITY_FIELD_BY_DISPLAY_NAME_MUTATION,
      variables: { displayName: EXAMPLE_DISPLAY_NAME, entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createEntityFieldByDisplayName: {
        ...EXAMPLE_ENTITY_FIELD,
        createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
      }
    });
    expect(createFieldByDisplayNameMock).toBeCalledTimes(1);
    expect(createFieldByDisplayNameMock).toBeCalledWith(
      {
        data: {
          displayName: EXAMPLE_DISPLAY_NAME,
          entity: { connect: { id: EXAMPLE_ID } }
        }
      },
      EXAMPLE_USER
    );
  });

  it('should delete an entity field', async () => {
    const res = await apolloClient.query({
      query: DELETE_ENTITY_FIELD_MUTATION,
      variables: { fieldId: EXAMPLE_ENTITY_FIELD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      deleteEntityField: {
        ...EXAMPLE_ENTITY_FIELD,
        createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
      }
    });
    expect(deleteFieldMock).toBeCalledTimes(1);
    expect(deleteFieldMock).toBeCalledWith(
      { where: { id: EXAMPLE_ENTITY_FIELD_ID } },
      EXAMPLE_USER
    );
  });

  it('should update an entity field', async () => {
    const res = await apolloClient.query({
      query: UPDATE_ENTITY_FIELD_MUTATION,
      variables: { fieldId: EXAMPLE_ENTITY_FIELD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      updateEntityField: {
        ...EXAMPLE_ENTITY_FIELD,
        createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
      }
    });
    expect(updateFieldMock).toBeCalledTimes(1);
    expect(updateFieldMock).toBeCalledWith(
      { data: {}, where: { id: EXAMPLE_ENTITY_FIELD_ID } },
      EXAMPLE_USER
    );
  });

  it('should create a default related field', async () => {
    const res = await apolloClient.query({
      query: CREATE_DEFAULT_RELATED_FIELD_MUTATION,
      variables: { fieldId: EXAMPLE_ENTITY_FIELD_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      createDefaultRelatedField: {
        ...EXAMPLE_ENTITY_FIELD_WITH_RELATION,
        createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
        updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
      }
    });
    expect(createDefaultRelatedFieldMock).toBeCalledTimes(1);
    expect(createDefaultRelatedFieldMock).toBeCalledWith(
      { where: { id: EXAMPLE_ENTITY_FIELD_ID } },
      EXAMPLE_USER
    );
  });

  //EntityVersion Resolver tests:

  it('should get a versions commit', async () => {
    const res = await apolloClient.query({
      query: GET_VERSION_COMMIT_QUERY,
      variables: { entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        versions: [
          {
            commit: {
              ...EXAMPLE_COMMIT,
              createdAt: EXAMPLE_COMMIT.createdAt.toISOString()
            }
          }
        ]
      }
    });
    expect(entityServiceGetVersionCommitMock).toBeCalledTimes(1);
    expect(entityServiceGetVersionCommitMock).toBeCalledWith(
      EXAMPLE_VERSION_ID
    );
  });

  it('should get entity version fields', async () => {
    const res = await apolloClient.query({
      query: GET_VERSION_FIELDS_QUERY,
      variables: { entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        versions: [
          {
            fields: [
              {
                ...EXAMPLE_ENTITY_FIELD,
                createdAt: EXAMPLE_ENTITY_FIELD.createdAt.toISOString(),
                updatedAt: EXAMPLE_ENTITY_FIELD.updatedAt.toISOString()
              }
            ]
          }
        ]
      }
    });
    expect(entityServiceGetVersionFieldsMock).toBeCalledTimes(1);
    expect(entityServiceGetVersionFieldsMock).toBeCalledWith(
      EXAMPLE_ID,
      EXAMPLE_VERSION_NUMBER,
      {}
    );
  });

  it('should get entity version permissions', async () => {
    const res = await apolloClient.query({
      query: GET_VERSION_PERMISSIONS_QUERY,
      variables: { entityId: EXAMPLE_ID }
    });
    expect(res.errors).toBeUndefined();
    expect(res.data).toEqual({
      entity: {
        versions: [
          {
            permissions: [
              {
                ...EXAMPLE_PERMISSION
              }
            ]
          }
        ]
      }
    });
    expect(entityServiceGetVersionPermissionsMock).toBeCalledTimes(1);
    expect(entityServiceGetVersionPermissionsMock).toBeCalledWith(
      EXAMPLE_ID,
      EXAMPLE_VERSION_NUMBER
    );
  });
});