Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.3k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...