sikanhe / gqtx

Code-first Typescript GraphQL Server without codegen or metaprogramming
458 stars 13 forks source link

Factory for making type maker #7

Closed sikanhe closed 4 years ago

sikanhe commented 4 years ago

This PR implements a factory function for make an object that holds all type helpers. The benefit is that you can set the context type on this builder function once, and all your schema type creators gets the correct context without manually asserting them.

import { createTypesFactory } from 'gqtx';

// createTypesFactory takes a context generic, and returns an object holds all type creators

type AppContext = {currentUserName: string};

const t = createTypesFactory<AppContext>();

const queryType = t.queryType({
  fields: [
    t.field('echo', {
      type: string,
      resolve: (
        _root, 
        _args, 
        ctx //: { currentUserName: string } - context type is alway correctly inferred across your entire application!
      ) => "hello " + ctx.currentUserName 
    })
  ],
});
n1ru4l commented 4 years ago

@sikanhe I am curious whether this kills the pattern where you can define partial contexts for your resolvers (and therefore hide all the stuff on the context object a specific resolver should not care about). Then when composing the schema a context object that satisfies all resolvers must be provided.

sikanhe commented 4 years ago

@n1ru4l I am not aware of what a partial context is, is this something new? It would be great to get a concret example with code or link to some other example on the internet.

Does partial just mean a subset of a full app context in terms of typescript?

sikanhe commented 4 years ago

https://www.typescriptlang.org/play/#code/C4TwDgpgBAygxgCwgWwIYB4DCB7AdsCAD2AD4oBeKAbylQBM6AlCAZ2wBsA3CAJwC4oACh6sO3fkLjBCAnPiLAAlBTKpcIZeTLwkaLHgLEyAXwDcAKHOhIUAGIBXduzmHgFalHsteASToCWYB4AS1wAcwAaT28eZjBsAKDQsIBtAF0oM0traAAFVB5gYNRnAwV3Gi9eOISoQJDw9MyLc3YINxE2Ll53QSkZKHzC4tL5Yk0yGizW9rrEFFQK41oWWHm9BycXBRJLFnXFyn3dVAA6eiZRbp5hK-FFFssgA

Example of defining partial context and still accepted by schema because of Structural typing for TS, is this what you're talking about?