The typeix/resty-graphql package: code-first schema generation, resolver scoping, query limits and error masking.¶
typeix/resty-graphql¶
Code-first GraphQL schema generation and HTTP server for the resty framework.
The schema is built from decorator metadata, resolvers are resolved through Typeix dependency injection, and the endpoint is mounted on the resty router after pipeServer, following the same convention as pipeWebSocket.
Requirements¶
- Node.js
^26.0.0 @typeix/resty^9.2.0graphql^16.0.0as a peer dependency
graphql is a peer on purpose: two copies of the package in one tree break instanceof checks inside the graphql executor.
Install¶
npm i @typeix/resty-graphql graphql
Quick start¶
import {createServer} from "http";
import {pipeServer, Injectable, Inject, Module, RootModule} from "@typeix/resty";
import {
pipeGraphQL, Resolver, Query, Mutation, ObjectType, InputType, Field, Args
} from "@typeix/resty-graphql";
@ObjectType()
class Book {
@Field()
id: string;
@Field()
title: string;
}
@InputType()
class AddBookInput {
@Field()
title: string;
}
@Injectable()
class BookService {
private readonly books = [{id: "1", title: "Dune"}];
list() {
return this.books;
}
add(title: string) {
return {id: String(this.books.length + 1), title};
}
}
@Resolver()
class BooksResolver {
@Inject() private service: BookService;
@Query(() => [Book])
books(): Book[] {
return this.service.list();
}
@Mutation(() => Book)
addBook(@Args() input: AddBookInput): Book {
return this.service.add(input.title);
}
}
@Module({providers: [BookService, BooksResolver], controllers: []})
class LibraryModule {
}
@RootModule({shared_providers: [], controllers: [], imports: [LibraryModule]})
class Application {
}
async function bootstrap() {
const server = createServer();
await pipeServer(server, Application);
await pipeGraphQL(server, Application, {path: "/graphql"});
server.listen(8080);
}
| Route | Content |
|---|---|
POST /graphql | query and mutation execution |
GET /graphql?query=... | queries only, a mutation over GET answers 405 and is not executed |
GET /graphql with Accept: text/html | built in playground |
GET /graphql/schema.graphql | SDL, with sdl: true |
Decorators¶
| Decorator | Level | Purpose |
|---|---|---|
@ObjectType({name, description}) | class | graphql object type |
@InputType({name, description}) | class | graphql input type |
@Field(() => Type, {nullable, description, deprecationReason, name, defaultValue}) | property | object or input field |
@HideField() | property | exclude a property from the schema |
@Resolver(() => ObjectType, {scope}) | class | resolver class, the thunk names the type for @ResolveField, scope is "request" (default) or "singleton" |
@Query(() => Type, {...}) | method | query field |
@Mutation(() => Type, {...}) | method | mutation field |
@ResolveField(() => Type, {...}) | method | field resolver on the @Resolver type |
@Args(name, () => Type) / @Args({name, type, nullable}) | parameter | bind an argument |
@Args() | parameter | flatten an @InputType into arguments |
@Parent(), @Context(), @Info() | parameter | graphql execution values |
EnumType(MyEnum, {name}) | function | name a TypeScript enum, a decorator cannot be applied to an enum |
Type thunks are required where TypeScript erases the type¶
emitDecoratorMetadata only reports constructors. It reports Promise for async methods, Array for lists, and Object for interfaces, type aliases, unions and import type. Those cases need an explicit thunk:
@Query(() => [Book]) // async list
books(): Promise<Book[]> {}
@ResolveField(() => Author) // circular reference
author(@Parent() book: Book) {}
Reflected metadata is used only when it is accurate: String, Number, Boolean, Date, Buffer and a decorated class used directly as the declared type.
Nullability¶
Fields are non-null by default, which matches graphql expectations and catches missing data early.
That has one consequence worth knowing: a non-null field whose resolver throws propagates the error to the nearest nullable parent. With non-null root fields one failing resolver makes the whole data null. Mark a field {nullable: true} when partial results are preferable.
Resolver scope¶
Resolvers default to request scope, which matches resty controllers: a fresh resolver instance per HTTP request, created from a child injector that is destroyed on response.finish.
@Resolver() // request scope, the default
class BooksResolver {}
@Resolver(undefined, {scope: "singleton"}) // one instance per process
class TaxonomyResolver {}
"request" (default) | "singleton" | |
|---|---|---|
| Instance | new per HTTP request | once, from the module injector |
| Injected services | module scoped, shared | module scoped, shared |
| Cost | one child injector per module per request | none after boot |
| Per request state | safe | must never be stored |
Only the resolver is per request, not the graph. A resolver that fans out over many items is still one instance for that operation, so a @ResolveField called per list item does not allocate per item.
Use "singleton" for stateless high fan out resolvers, and "request" whenever the resolver holds per request state or needs the request itself.
Dependency injection¶
- Resolvers are resolved per resolver from the module that declares them, so a resolver declared in an imported module is created from that module's injector.
- Constructor and property injection work as usual.
- A handler parameter without a graphql decorator is injected, not bound to an argument:
@Query(() => Book)
book(@Args("id") id: string, service: BookService) { // service is injected
return service.find(id);
}
providers versus controllers¶
resty instantiates every module providers entry at boot, before any request exists. That has two effects:
- A resolver declared in
providersis constructed once at boot even when its scope is"request", so its constructor must not depend on request state. - Injecting
IncomingMessage/ServerResponseinto a resolver declared inprovidersfails duringpipeServerwithNo provider IncomingMessage. This is a resty constraint, not a graphql one.
Declare the resolver in controllers instead when it has to inject the request: controllers are created lazily, so the request is available, and resty's router ignores them because they have no @Controller decorator.
@Module({providers: [], controllers: [RequestAwareResolver]})
Request injection only works for request scope; a "singleton" resolver declared in controllers is not in the module injector and is rejected. The portable way to reach the request is always @Context().
Context¶
The context is created per request:
await pipeGraphQL(server, Application, {
contextFactory: injector => ({loaders: createLoaders(), user: undefined, injector})
});
injector, request and response are added when the returned object does not define them. Use @Context() to read it, which is the natural place for per-request dataloaders.
HTTP behaviour¶
Status codes follow the GraphQL-over-HTTP specification for the behaviours implemented here:
| Situation | Status |
|---|---|
Execution with errors, data present or null | 200 |
| Syntax or validation error, no execution | 400 |
| Malformed JSON body or missing query | 400 |
Mutation or subscription sent over GET | 405 |
Batch larger than maxBatchSize | 400 |
Batching is disabled by default; enable it with maxBatchSize.
Options¶
| Option | Default | Description |
|---|---|---|
path | "/graphql" | mount path |
strict | true | throw on schema diagnostics instead of degrading a field |
introspection | true | set to false to block __schema queries |
maxBatchSize | 0 | 0 disables batching |
contextFactory | – | build the per request context |
ui | true | serve the built in playground on an html request |
title | "GraphQL" | playground title |
sdl | false | expose {path}/schema.graphql |
maxDepth | – | reject deeper selection sets |
maxFieldCount | – | reject operations selecting more fields |
maskErrors | false | replace resolver error messages |
maskedMessage | "Internal server error" | message used when masking |
includeExtensions | false | keep extensions on masked errors |
onError | – | log every error before masking |
Limits and error masking¶
Both exist because the default graphql behaviour trusts the client.
Query limits¶
await pipeGraphQL(server, Application, {
path: "/graphql",
maxDepth: 8,
maxFieldCount: 200
});
maxDepth counts selection set nesting, fragments are transparent and inline fragments add no depth. maxFieldCount counts field selections including aliases, with fragments expanded. Both are measured per operation, so an unused cheap operation does not mask an expensive one. A breach answers 400 before validation runs.
These are structural guards, not cost analysis: every field counts as 1, so a field backed by a full table scan costs the same as a scalar. For a real cost model, weigh fields per schema and add a persisted query allowlist or a reverse proxy timeout.
Error masking¶
await pipeGraphQL(server, Application, {
maskErrors: true,
onError: error => logger.error(error.originalError ?? error)
});
maskErrors replaces messages of execution errors only, meaning errors carrying a path, i.e. thrown by a resolver. Parse and validation errors describe client input and keep their message. path and locations are kept so a client can still tell which field failed. extensions are dropped unless includeExtensions: true, because extensions regularly carry database payloads.
onError always sees the real error, masked or not. Masking without onError throws the information away.
// maskErrors: true
{"data": null, "errors": [{"message": "Internal server error", "path": ["books"]}]}
Build time usage¶
import {GraphQLModule} from "@typeix/resty-graphql";
const sdl = GraphQLModule.printSchema(Application);
await fs.writeFile("schema.graphql", sdl, "utf8");
The static scanner walks the module graph without booting a server or instantiating providers. A runtime and a static schema are printed identically, which makes a CI schema diff meaningful.
Diagnostics¶
Schema problems are collected, attached to the schema under a symbol, and never printed into SDL:
[resty-graphql] warn: Book.author: reflected type is erased (interface, union or import type), pass an explicit thunk
[resty-graphql] warn: type name "User" is already used, renamed to "User1"
[resty-graphql] warn: UsersResolver.me: parameter 0 binds all arguments but has no @InputType type
strict defaults to true, so a schema that would silently lose a field fails at boot instead. Set strict: false to get a degraded schema plus diagnostics, for example while migrating.
Read them at runtime with GraphQLModule.getDiagnostics(schema).
Not implemented yet¶
- Subscriptions. They need the
graphql-wsprotocol on top ofresty-ws, a different lifecycle than HTTP. requestinjection fromproviders. resty creates providers at boot, declare the resolver incontrollersif it needs the request.- Interfaces and unions. Only object and input types are generated.
- SDL-first schemas. The code-first path only.
- Federation.
- Automatic type thunks. A TypeScript transformer could infer
() => Type, it is a separate project. - Custom scalars as field types. Scalar mapping is driven by the declared type:
String,Number,Boolean,Date(→DateTime),Buffer(→Base64) andBigInt(→String). Passing a scalar instance such asDateTimeas a field type thunk is rejected. TheJSONscalar is exported but not reachable for an erasedObjectproperty. - Query cost analysis.
maxDepthandmaxFieldCountare structural guards; a real cost model with per field weights is not implemented. application/graphql-response+json. Onlyapplication/jsonis produced; the newer media type from the GraphQL-over-HTTP spec is not negotiated.- Persisted queries and
@defer/@stream. Not supported.