@nestjs/graphql#ID TypeScript Examples

The following examples show how to use @nestjs/graphql#ID. 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: form.delete.mutation.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
@Mutation(() => DeletedModel)
  @Roles('admin')
  async deleteForm(
    @User() user: UserEntity,
    @Args('id', {type: () => ID}, FormByIdPipe) form: FormEntity,
  ): Promise<DeletedModel> {
    if (!form.isLive && !this.formService.isAdmin(form, user)) {
      throw new Error('invalid form')
    }

    await this.deleteService.delete(form.id)

    return new DeletedModel(this.idService.encode(form.id))
  }
Example #2
Source File: user.resolver.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
@Subscription(() => UserType, {
    filter: (payload, variables: { id: string }) => {
      return payload.userAdded.id === variables.id;
    },
    resolve: (payload) => {
      return payload.userAdded;
    },
  })
  async specificUserAdded(
    @Args({ name: 'id', type: () => ID }) id: string,
    @Context() ctx: MercuriusContext,
  ) {
    return toAsyncIterator(ctx.pubsub.subscribe('USER_ADDED'));
  }
Example #3
Source File: setting.query.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
@Query(() => SettingModel)
  getSetting(
    @Args('key', {type: () => ID}) key: string,
    @User() user: UserEntity,
  ): SettingModel {
    if (!this.settingService.isPublicKey(key) && !user.roles.includes('superuser')) {
      throw new Error(`no access to key ${key}`)
    }

    return this.settingService.getByKey(key)
  }
Example #4
Source File: cat.resolver.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
@Query(() => Cat, { nullable: true })
  cat(@Args({ name: 'id', type: () => ID }, ParseIntPipe) id: number) {
    return this.catService.cat(id);
  }
Example #5
Source File: user.model.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
@Field(() => ID)
  readonly id: string
Example #6
Source File: auth.schema.ts    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
@Field(() => ID, { nullable: false })
  readonly _id: string;
Example #7
Source File: article.model.ts    From prisma-nestjs-graphql with MIT License 5 votes vote down vote up
@Field(() => ID, { nullable: false })
  id!: string;
Example #8
Source File: user.type.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
@Field(() => ID)
  id: string;
Example #9
Source File: notification.model.ts    From aws-nestjs-starter with The Unlicense 5 votes vote down vote up
@Field(/* istanbul ignore next */ () => ID)
  id: string;
Example #10
Source File: whisp.entity.ts    From whispr with MIT License 5 votes vote down vote up
@Field(() => ID)
  _id: string;
Example #11
Source File: user.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
@Field(() => ID)
  id: number;
Example #12
Source File: form.hook.model.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
@Field(() => ID)
  readonly id: string
Example #13
Source File: post.type.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
@Field(() => ID)
  id: string;
Example #14
Source File: notification.resolver.ts    From aws-nestjs-starter with The Unlicense 5 votes vote down vote up
@Query(/* istanbul ignore next */ () => Notification)
  notification(
    @Args('id', { type: /* istanbul ignore next */ () => ID }) id: string,
  ) {
    return this.notificationService.findOne({ id });
  }
Example #15
Source File: form.model.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
@Field(() => ID)
  readonly id: string
Example #16
Source File: dbms.types.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
@Field(() => ID)
    id: string;
Example #17
Source File: notification.resolver.ts    From aws-nestjs-starter with The Unlicense 5 votes vote down vote up
@Mutation(/* istanbul ignore next */ () => Notification)
  updateNotification(
    @Args('id', { type: /* istanbul ignore next */ () => ID }) id: string,
    @Args('input') input: UpdateNotificationInput,
  ) {
    return this.notificationService.update({ id }, input);
  }
Example #18
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]`));
    });
  });
});