Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

sequelize.js - How to use sequelize-typescript for querying relative objects through custom Apollo GraphQL resolver?

How to use sequelize-typescript for querying relative objects through custom Apollo GraphQL type? I have the following query without typescript:

User and Event GraphQL types:

type User {
    id: Int
    login: String
    email: String
    role: Roles
    url_identity: String
}

type Event {
  id: Int
  event_name: String
  user: User
}

User model

import {HasOne, Model, Table} from "sequelize-typescript";
import Event from "./event.model";

@Table({
    timestamps: false,
    modelName: 'User',
})
export default class User extends Model {

    @HasOne(() => Event)
    event: Event
}

Resolver:

static resolver() {
    return {
        Event: {
            user: event => event.$get('user')
    }
}

Typescript can't see event.$get('user')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The answer is to add mappers to your graphql-codegen config. You can also pass interface for context (third parameter):

schema: ./src/graphql/types/**/*.graphql
generates:
  ./src/graphql/resolvers-types.ts:
    config:
      useIndexSignature: true
      contextType: ./schema#IApolloServerContext
      mappers:
        Event: ../database/models/event.model#EventModel
        User: ../database/models/user.model#UserModel
    plugins:
      - typescript
      - typescript-resolvers

More info here: https://graphql-code-generator.com/docs/plugins/typescript-resolvers#use-your-model-types-mappers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...