Skip to content

Instantly share code, notes, and snippets.

@beeman
Created April 26, 2020 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beeman/0d861d673531621b8c9706cca8cf4f43 to your computer and use it in GitHub Desktop.
Save beeman/0d861d673531621b8c9706cca8cf4f43 to your computer and use it in GitHub Desktop.
GraphQL Crud Decorators

For my NestJS API I want to be able to automatically generate my GraphQL CRUD code that I keep on repeating, based on the model that I want to work on.

This is very similar to what for instance nestjsx/crud does for Rest API's.

Another similar project is doug-martin/nestjs-query

The API I'd like to use is the following:

// Create an interface that extends the base interface
export interface MyUser extends CrudUser {}

// Create a service that extends the base service.
export interface MyUserService implements CrudService<MyUser> {
  // Here we implement the expected operations:
  findMany(): Promise<MyUser> {}
  findOne(id: string): Promise<MyUser> {}
  create(input: Partial<MyUser>): Promise<MyUser> {}
  update(id: string, input: Partial<MyUser>): Promise<MyUser> {}
  delete(id: string): Promise<MyUser> {}
  
  // We should be able to extend the Service here
}

// Create a resolver and pass in our service
@Crud({
  model: MyUser,
})
@Resolver()
export class MyUserResolver extends CrudResolver<MyUser> {
  constructor(private readonly service: MyUserService) {}
  
  // We should be able to extend the resolver here
}

Using the MyUserResolver should lead to the following GraphQL operations:

@Query(() => [MyUser])
myUsers() {
  return this.service.findMany()
}

@Query(() => MyUser)
myUser(@Args('id') id: string) {
  return this.service.findOne(id)
}

@Mutation(() => MyUser)
create(input: Partial<MyUser>) {
  return this.service.create(input)
}

@Mutation(() => MyUser)
update(id: string, input: Partial<MyUser>) {
  return this.service.update(id, input)
}

@Mutation(() => Boolean)
delete(id: string) {
  return this.service.delete(id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment