npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nyalajs/graphql

v0.1.1

Published

Code-first GraphQL (resolvers, guards, interceptors, DataLoader batching, subscriptions) for NyalaJS, sharing the same DI/tenancy pipeline as HTTP and microservices

Downloads

310

Readme

@nyalajs/graphql

Code-first GraphQL for Nyala.js. @Resolver()/@Query()/@Mutation()/@Subscription() classes are resolved through the same DI container, multi-tenancy pipeline, and @UseGuards()/@UseInterceptors()/@UseFilters() decorators as @nyalajs/http controllers and @nyalajs/microservices message patterns — one guard implementation can protect a REST route, a message pattern, and a GraphQL field.

Quick start

import { ObjectType, Field, ID, Resolver, Query, Args } from "@nyalajs/graphql";

@ObjectType()
class User {
  @Field(() => ID) id!: string;
  @Field(() => String) name!: string;
}

@Injectable()
@Resolver()
class UserResolver {
  constructor(private users: UsersService) {}

  @Query(() => [User])
  users() {
    return this.users.findAll();
  }

  @Query(() => User, { nullable: true })
  user(@Args("id", () => ID) id: string) {
    return this.users.findOne(id);
  }
}
import { FastifyAdapter } from "@nyalajs/http";
import { GraphqlServer, mountGraphqlServer } from "@nyalajs/graphql";

const httpAdapter = new FastifyAdapter();
const server = new GraphqlServer(kernel, { resolvers: [UserResolver] });
await mountGraphqlServer(httpAdapter.getInstance(), server);
// GET/POST /graphql now serves the schema, plus GraphiQL in dev.

Resolvers, guards, interceptors, and filters must all be registered as DI providers in your module — the dispatcher resolves them through Container.resolve(), same as any other injectable:

@Module({ providers: [UserResolver, AdminOnlyGuard] })
class AppModule {}

Why a required type thunk

@Field(() => String) always needs its thunk — there's no @Field() bare-form fallback. TypeScript's design:type reflect-metadata (the mechanism NestJS's/TypeGraphQL's optional-thunk convenience relies on) is only emitted by tsc with emitDecoratorMetadata, and is silently absent under esbuild/SWC-based dev/test tooling. A bare @Field() would work in a production tsc build and silently resolve to undefined everywhere else — the thunk is required so a missing type fails loudly and consistently instead.

The same convention applies to @Query(), @Mutation(), @Subscription(), @Args(name, type), and @ResolveField() return types. List types use the () => [User] array-literal shorthand (TypeGraphQL's own convention) rather than a separate { list: true } option, though { list: true } is still honored if you prefer spelling it out.

Guards, interceptors, filters

@Query(() => Secret)
@UseGuards(AdminOnlyGuard)
@UseInterceptors(LoggingInterceptor)
adminSecret() { ... }

GraphqlGuard/GraphqlInterceptor/GraphqlExceptionFilter mirror @nyalajs/http's Guard/Interceptor/exception filter contracts exactly, retargeted to a GraphqlExecutionContext ({ args, parent, ctx, info, container, resolverClass, handlerName, operationKind }) instead of an HTTP request/response. A guard returning false throws GraphqlPermissionDeniedError, which — per GraphQL's own null-propagation rules — nulls the whole response's data if the blocked field isn't nullable, not just that one field.

Field resolvers (@ResolveField)

@Injectable()
@Resolver(() => Post)
class PostFieldResolver {
  @ResolveField(() => User, { nullable: true })
  async author(@Parent() post: Post, @Ctx() ctx: GraphqlContext) {
    let loader = ctx.loaders.get(PostFieldResolver);
    if (!loader) {
      loader = createLoader(async (ids: readonly string[]) => {
        const users = await this.users.findByIds(ids);
        return ids.map((id) => users.find((u) => u.id === id) ?? null);
      });
      ctx.loaders.set(PostFieldResolver, loader);
    }
    return loader.load(post.authorId);
  }
}

@ResolveField() either overrides a field the target @ObjectType() already declares with @Field(), or adds an entirely new field the class has no property for (the common case — Post.author computed from Post.authorId). A return type thunk is required unless overriding an already-@Field()-declared field.

DataLoader batching (N+1)

ctx.loaders is a fresh Map every request — create and cache loaders there, never at module scope. A module-level DataLoader is a cross-tenant data leak waiting to happen: it would cache across requests and across tenants, so tenant B's resolver could receive a row DataLoader cached from tenant A's query.

Multi-tenancy

const server = new GraphqlServer(kernel, {
  resolvers: [...],
  tenantResolvers: [new HeaderTenantResolver(), new JwtTenantResolver()],
});

Works with @nyalajs/tenancy's real resolvers directly (or any object implementing resolve(request): Promise<string | undefined>). Each request runs inside its own TenantContext.run()/LogContext.run() scope, exactly like @nyalajs/http's FastifyAdapterTenantContext.get() inside a resolver, or inside a service/Model a resolver calls into, behaves identically whether reached via REST or GraphQL.

Subscriptions

@Subscription(() => Tick)
async *ticks() {
  while (true) {
    yield { count: ++n };
    await sleep(1000);
  }
}

Delivered over Server-Sent Events through the same /graphql endpoint (accept: text/event-stream) — no separate WebSocket server. A resolver method returning an AsyncGenerator/AsyncIterable is the subscribe step by default; pass { subscribe: "methodName" } to split subscribe and resolve into separate methods.

Error masking

Unset by default — matching graphql-yoga's own safe default, an unexpected resolver error's message is replaced with "Unexpected error." in the response rather than leaking internal detail (stack traces, database error text) to API clients. Set maskedErrors: false on GraphqlServerOptions for local development, or if every error your resolvers throw is already meant to be shown verbatim.

Peer dependencies

graphql is a required peer dependency (install it alongside this package) — deliberately not bundled as a direct dependency, because a direct dependency lets npm install a second, separately-hoisted copy of graphql alongside whatever copy graphql-yoga (or your app) already has. graphql-js's own runtime identity checks (assertSchema, instanceof GraphQLSchema) then reject a real schema built against one copy when executed against the other, reporting it as "from another module or realm" even though nothing is actually wrong with it. Only one graphql in the tree — which a peer dependency guarantees — avoids this entirely.

graphql-yoga is an optional peer dependency — only required if you call mountGraphqlServer(). Pin both to versions compatible with graphql-yoga@^5.x (which itself requires graphql@^16.x).

npm install graphql graphql-yoga

A note on graphql-js and Vitest

graphql-js ships both a CJS build and an ESM build with no unifying exports map. If your resolvers/schema-builder code and graphql-yoga's own internals end up loading different copies (one via require, one via import), graphql-js's own runtime identity checks reject a real schema as "from another module or realm." If you hit this under Vitest, alias graphql to its resolved path in vitest.config.ts:

import { createRequire } from "node:module";
const require = createRequire(import.meta.url);

export default defineConfig({
  resolve: { alias: { graphql: require.resolve("graphql") } },
});

What's NOT included

  • No schema stitching/federation — one GraphqlServer builds one schema from the resolver classes you list. Composing multiple services' schemas into one graph (Apollo Federation-style) is out of scope.
  • No automatic persisted queries / query allowlisting — bring your own graphql-yoga plugin if you need this.
  • No built-in rate limiting per-field — use a GraphqlInterceptor or GraphqlGuard, or rate-limit at the HTTP layer in front of /graphql.