Skip to content
Browse files

release: 0.17.0

  • Loading branch information...
19majkel94 committed Mar 3, 2019
1 parent efe5371 commit 37a2d10a246de9bc86fa3e162b89750702914b95
Showing with 2,751 additions and 6 deletions.
  1. +4 −3
  2. +1 −1 package-lock.json
  3. +1 −1 package.json
  4. +165 −0 website/versioned_docs/version-0.17.0/
  5. +115 −0 website/versioned_docs/version-0.17.0/
  6. +22 −0 website/versioned_docs/version-0.17.0/
  7. +84 −0 website/versioned_docs/version-0.17.0/
  8. +148 −0 website/versioned_docs/version-0.17.0/
  9. +35 −0 website/versioned_docs/version-0.17.0/
  10. +85 −0 website/versioned_docs/version-0.17.0/
  11. +42 −0 website/versioned_docs/version-0.17.0/
  12. +79 −0 website/versioned_docs/version-0.17.0/
  13. +132 −0 website/versioned_docs/version-0.17.0/
  14. +188 −0 website/versioned_docs/version-0.17.0/
  15. +145 −0 website/versioned_docs/version-0.17.0/
  16. +72 −0 website/versioned_docs/version-0.17.0/
  17. +52 −0 website/versioned_docs/version-0.17.0/
  18. +51 −0 website/versioned_docs/version-0.17.0/
  19. +209 −0 website/versioned_docs/version-0.17.0/
  20. +343 −0 website/versioned_docs/version-0.17.0/
  21. +166 −0 website/versioned_docs/version-0.17.0/
  22. +185 −0 website/versioned_docs/version-0.17.0/
  23. +123 −0 website/versioned_docs/version-0.17.0/
  24. +84 −0 website/versioned_docs/version-0.17.0/
  25. +172 −0 website/versioned_docs/version-0.17.0/
  26. +44 −0 website/versioned_sidebars/version-0.17.0-sidebars.json
  27. +4 −1 website/versions.json
@@ -1,16 +1,17 @@
# Changelog and release notes

## Unreleased
<!-- ## Unreleased -->
<!-- here goes all the unreleased changes descriptions -->

## v0.17.0
### Features
- **Breaking Change**: make `graphql-js` packages a peer dependencies, bump `graphql` to `^14.1.1` and `@types/graphql` to `^14.0.7` (#239)
- **Breaking Change**: remove `useContainer` function and allow to register container by `buildSchema` options (#241)
- **Breaking Change**: change the default `PrintSchemaOptions` option `commentDescriptions` to false (no more `#` comments in SDL)
- add support for passing `PrintSchemaOptions` in `buildSchema.emitSchemaFile` (e.g. `commentDescriptions: true` to restore previous behavior)
- add `buildTypeDefsAndResolvers` utils function for generating apollo-like `typeDefs` and `resolvers` pair (#233)
- add support for generic types (#255)

## Fixes
### Fixes
- **Breaking Change**: remove the `formatArgumentValidationError` helper as it's not compatible and not needed in new Apollo Server (#258)
- fix calling return type getter function `@Field(type => Foo)` before finishing module evaluation (allow for extending circular classes using `require`)
- fix nullifying other custom method decorators - call the method on target instance, not the stored reference to original function (#247)

Some generated files are not rendered by default. Learn more.

@@ -1,6 +1,6 @@
"name": "type-graphql",
"version": "0.16.0",
"version": "0.17.0",
"author": {
"name": "Michał Lytek",
"url": ""
@@ -0,0 +1,165 @@
title: Authorization
id: version-0.17.0-authorization
original_id: authorization

Authorization is a core feature used in almost all APIs. Sometimes we want to restrict access to some actions or reading some data only for specific group of users.

In express.js (and other Node.js framework) we use middlewares for this, like `passport.js` or the custom ones. However in GraphQL's resolvers architecture we don't have middlewares so we have to imperatively call the auth checking function and manually passing context data in each resolver, which might be quite tedious work.

And that's why authorization is a first-class feature in `TypeGraphQL`!

## How to use?

At first, you need to use `@Authorized` decorator as a guard on a field or a query/mutation.
Example object type's fields guards:

class MyObject {
publicField: string;
authorizedField: string;
adminField: string;
@Authorized(["ADMIN", "MODERATOR"])
@Field({ nullable: true })
hiddenField?: string;

You can leave the `@Authorized` decorator brackets empty or you can specify the roles that the user needs to have to get access to the field, query or mutation.
By default the roles are `string` but you can change it easily as the decorator is generic - `@Authorized<number>(1, 7, 22)`.

This way authed users (regardless of theirs roles) could read only `publicField` or `authorizedField` from `MyObject` object. They will receive `null` when accessing `hiddenField` field and will receive error (that will propagate through the whole query tree looking for nullable field) for `adminField` when they don't satisfy roles constraints.

Sample query and mutations guards:

class MyResolver {
publicQuery(): MyObject {
return {
publicField: "Some public data",
authorizedField: "Data only for logged users",
adminField: "Top secret info for admin",
authedQuery(): string {
return "Only for authed users!";
@Authorized("ADMIN", "MODERATOR")
adminMutation(): string {
return "You are an admin/moderator, you can safely drop database ;)";

Authed users (regardless of theirs roles) will be able to read data from `publicQuery` and `authedQuery` but will receive error trying to perform `adminMutation` when their roles doesn't include `ADMIN` or `MODERATOR`.

In next step, you need to create your auth checker function. Its implementation may depends on your business logic:

export const customAuthChecker: AuthChecker<ContextType> = (
{ root, args, context, info },
) => {
// here you can read user from context
// and check his permission in db against `roles` argument
// that comes from `@Authorized`, eg. ["ADMIN", "MODERATOR"]
return true; // or false if access denied

The second argument of `AuthChecker` generic type is `RoleType` - use it together with `@Authorized` decorator generic type.

The last step is to register the function while building the schema:

import { customAuthChecker } from "../auth/custom-auth-checker.ts";
const schema = await buildSchema({
resolvers: [MyResolver],
// here we register the auth checking function
// or defining it inline
authChecker: customAuthChecker,

And it's done! 😉

If you need silent auth guards and you don't want to return auth errors to users, you can set `authMode` property of `buildSchema` config object to `"null"`:

const schema = await buildSchema({
resolvers: ["./**/*.resolver.ts"],
authChecker: customAuthChecker,
authMode: "null",

It will then return `null` instead of throwing authorization error.

## Recipes

You can also use `TypeGraphQL` with JWT authentication. Example using `apollo-server-express`:

import express from "express";
import { ApolloServer, gql } from "apollo-server-express";
import * as jwt from "express-jwt";
import { schema } from "../example/above";
const app = express();
const path = "/graphql";
// Create a GraphQL server
const server = new ApolloServer({
context: ({ req }) => {
const context = {
user: req.user, // `req.user` comes from `express-jwt`
return context;
// Mount a jwt or other authentication middleware that is run before the GraphQL execution
secret: "TypeGraphQL",
credentialsRequired: false,
// Apply the GraphQL server middleware
server.applyMiddleware({ app, path });
// Launch the express server
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`),

Then you can use standard, token based authorization in HTTP header like in classic REST API and take advantages of `TypeGraphQL` authorization mechanism.

## Example

You can see how this works together in the [simple real life example](
@@ -0,0 +1,115 @@
title: Bootstrapping
id: version-0.17.0-bootstrap
original_id: bootstrap

After creating our resolvers, types classes, and other business-related code, we need to make our app run. First we have to build the schema, then we can expose it by HTTP server, WebSockets or even MQTT.

## Create Executable Schema

To create an executable schema from type and resolver definitions, you need to use the `buildSchema` function.
It takes a configuration object as a parameter and returns a promise of a `GraphQLSchema` object.

In the configuration object you must provide a `resolvers` property, which can be an array of resolver classes:

import { FirstResolver, SecondResolver } from "../app/src/resolvers";
// ...
const schema = await buildSchema({
resolvers: [FirstResolver, SampleResolver],

However, when there are several dozen of resolver classes, manual imports can be tedious.
So you can also provide an array of paths to resolver module files instead, which can include globs:

const schema = await buildSchema({
resolvers: [__dirname + "/modules/**/*.resolver.ts", __dirname + "/resolvers/**/*.ts"],

There are also other options related to advanced features like [authorization]( or [validation]( - you can read about them in docs.

To make `await` work, we need to declare it as an async function. Example of `main.ts` file:

import { buildSchema } from "type-graphql";
async function bootstrap() {
const schema = await buildSchema({
resolvers: [__dirname + "/**/*.resolver.ts"],
// other initialization code, like creating http server
bootstrap(); // actually run the async function

## Create HTTP GraphQL endpoint

In most cases, the GraphQL app is served by a HTTP server. After building the schema we can create the GraphQL endpoint with a variety of tools such as [`graphql-yoga`]( or [`apollo-server`]( Here is an example using [`apollo-server`](

import { ApolloServer } from "apollo-server";
const PORT = process.env.PORT || 4000;
async function bootstrap() {
// ... Building schema here
// Create GraphQL server
const server = new ApolloServer({
playground: true,
// Start the server
const { url } = await server.listen(PORT);
console.log(`Server is running, GraphQL Playground available at ${url}`);

Remember to install `apollo-server` package from npm - it's not bundled with TypeGraphQL.

Of course you can use `express-graphql` middleware, `graphql-yoga` or whatever you want 😉

## Create typeDefs and resolvers map

TypeGraphQL also provides a second way to generate the GraphQL schema - the `buildTypeDefsAndResolvers` function.

It accepts the same `BuildSchemaOptions` like the `buildSchema` function but instead of an executable `GraphQLSchema`, it creates a typeDefs and resolversMap pair that you can use e.g. with [`graphql-tools`](

import { makeExecutableSchema } from "graphql-tools";
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({
resolvers: [FirstResolver, SecondResolver],
const schema = makeExecutableSchema({ typeDefs, resolvers });

Or even with other libraries that expect the schema info in that shape, like [`apollo-link-state`](

import { withClientState } from "apollo-link-state";
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({
resolvers: [FirstResolver, SecondResolver],
const stateLink = withClientState({
// ...other options like `cache`
// ...the rest of `ApolloClient` initialization code

Be aware that some of the TypeGraphQL features (i.a. [query complexity]( might not work with `buildTypeDefsAndResolvers` approach because they use some low-level `graphql-js` features.
@@ -0,0 +1,22 @@
title: Browser usage
id: version-0.17.0-browser-usage
original_id: browser-usage

## Using classes in client app

Sometimes you might want to use the classes, that you've created and annotated with TypeGraphQL decorators, in your client app that works in browser. For example, you may want to reuse the args or input classes with `class-validator` decorators or the object type classes with some helpful custom methods.

As TypeGraphQL is a Node.js framework, it doesn't work in browser environment, so you may quickly got an error, e.g. `ERROR in ./node_modules/fs.realpath/index.js`, while trying to build your app with Webpack. To fix that, you have to configure Webpack to use the decorators shim instead of normal module. All you need is to add this plugin code to your webpack config:

plugins: [
// are any other existing plugins that you already have
new webpack.NormalModuleReplacementPlugin(/type-graphql$/, resource => {
resource.request = resource.request.replace(/type-graphql/, "type-graphql/dist/browser-shim");

Also, thanks to this your bundle will be much lighter as you don't embedded the whole TypeGraphQL library code in your app.

0 comments on commit 37a2d10

Please sign in to comment.
You can’t perform that action at this time.