Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Create GraphQL schema with TypeScript classes.

License

NotificationsYou must be signed in to change notification settings

prismake/typegql

Repository files navigation

npm versionnpm versioncodecovBuild Status

What istypegql?

demo

typegql is set of decorators allowing creating GraphQL APIs quickly and in type-safe way.

Examples:

Basic example

Example below is able to resolve such query

query {hello(name:"Bob") # will resolve to 'Hello, Bob!'}
import{compileSchema,SchemaRoot,Query}from'typegql';@SchemaRoot()classSuperSchema{  @Query()hello(name:string):string{return`Hello,${name}!`;}}constcompiledSchema=compileSchema({roots:[SuperSchema]});

compiledSchema is regular executable schema compatible withgraphql-js library.

To use it withexpress, you'd have to simply:

import*asexpressfrom'express';import*asgraphqlHTTPfrom'express-graphql';constapp=express();app.use('/graphql',graphqlHTTP({schema:compiledSchema,graphiql:true,}),);app.listen(3000,()=>console.log('Graphql API ready on http://localhost:3000/graphql'));

Adding nested types

For now, our query field returned scalar (string). Let's return something more complex. Schema will look like:

mutation {createProduct(name:"Chair",price:99.99) {namepriceisExpensive  }}

Such query will have a bit more code and here it is:

import{Schema,Query,ObjectType,Field,Mutation,compileSchema}from'typegql';@ObjectType({description:'Simple product object type'})classProduct{  @Field()name:string;  @Field()price:number;  @Field()isExpensive(){returnthis.price>50;}}@Schema()classSuperSchema{  @Mutation()createProduct(name:string,price:number):Product{constproduct=newProduct();product.name=name;product.price=price;returnproduct;}}constcompiledSchema=compileSchema(SuperSchema);

Forcing field type.

Until now,typegql was able to guess type of every field from typescript type definitions.

There are, however, some cases where we'd have to define them explicitly.

  • We want to strictly tell if field is nullable or not
  • We want to be explicit about if somenumber type isFloat orInt (GraphQLFloat orGraphQLInt) etc
  • Function we use returns type ofPromise<SomeType> while field itself is typed asSomeType
  • List (Array) type is used. (For now, typescriptReflect api is not able to guess type of single array item. This might change in the future)

Let's modify ourProduct so it has additionalcategories field that will return array of strings. For sake of readibility, I'll ommit all fields we've defined previously.

@ObjectType()classProduct{  @Field({type:[String]})// note we can use any native type like GraphQLString!categories():string[]{return['Tables','Furniture'];}}

We've added{ type: [String] } as@Field options. Type can be anything that is resolvable toGraphQL type

  • Native JS scalars:String,Number,Boolean.
  • Any type that is already compiled tographql eg.GraphQLFloat or any type from external graphql library etc
  • Every class decorated with@ObjectType
  • One element array of any of above for list types eg.[String] or[GraphQLFloat]

Writing Asynchronously

Every field function we write can beasync and returnPromise. Let's say, instead of hard-coding our categories, we want to fetch it from some external API:

@ObjectType()classProduct{  @Field({type:[String]})// note we can use any native type like GraphQLString!asynccategories():Promise<string[]>{constcategories=awaitapi.fetchCategories();returncategories.map(cat=>cat.name);}}

Before1.0.0

Before version1.0.0 consider APIs oftypegql to be subject to change. We encourage you to try this library out and provide us feedback so we can polish it to be as usable and efficent as possible.


[8]ページ先頭

©2009-2025 Movatter.jp