/egg-type-graphql

TypeGrapQL plugin for Egg

Primary LanguageTypeScriptMIT LicenseMIT

egg-type-graphql

TypeGraphQL plugin for Egg.js.

NPM version npm download

Install

$ yarn add egg-type-graphql

Usage

Plugin

// {app_root}/config/plugin.ts
const plugin: EggPlugin = {
  typeGraphQL: {
    enable: true,
    package: 'egg-type-graphql',
  },
}

Configuration

// {app_root}/config/config.default.ts
config.typeGraphQL = {
  router: '/graphql',
  dateScalarMode: 'isoDate',
}

Resovler files

.
├── controller
│   └── home.ts
├── directive
│   ├── dateFormat.ts
│   └── upperCase.ts
├── public
├── recipe
│   ├── resolver
│   │   ├── recipe.resolver.ts
│   │   └── sample.resolver.ts
│   └── type
│       └── notification.ts
├── router.ts
└── service
    └── Test.ts

Usage

// service

import { Service } from 'typedi';

@Service()
export class UserService {
  getUser() {
    // TODO
  }

  queryUser() {
    // TODO
  }
}
// {app_root}/app/resolver/user.ts
import { Resolver, Query } from 'type-graphql'
import { User } from './User.type'

@Resolver(() => User)
export class UserResolver {
  constructor(private userService: UserService) {}

  @Query(() => [User])
  async user(): Promise<User> {
    return await this.userService.getUser()
  }

  @Query(() => [User])
  async users(): Promise<User[]> {
    return await this.userService.queryUser()
  }
}

example

Use Directive

In config:

config.typeGraphQL = {
  router: '/graphql',
  dateScalarMode: 'isoDate',
  typeDefs: `
      directive @upperCase on FIELD_DEFINITION | FIELD
      directive @dateFormat(format: String) on FIELD_DEFINITION | FIELD
    `,
}

Create a Directive:

// app/directive/upperCase.ts
export default async function upperCase({ resolve }) {
  const value = await resolve()
  return value.toString().toUpperCase()
}

Create a Directive with args:

// app/directive/dateFormat.ts
import { format } from 'date-fns'

const dateFormat = async ({ resolve, args }) => {
  const value = await resolve()

  if (value instanceof Date) {
    return format(value, args.format)
  }

  return format(new Date(value), args.format)
}

export default dateFormat

Questions & Suggestions

Please open an issue here.

License

MIT