Skip to content
Browse files

release: 0.17.1

  • Loading branch information...
19majkel94 committed Mar 29, 2019
1 parent 8a31741 commit f8b85e3688efe70c18b51d8384f09d416e4d2772
Showing with 2,723 additions and 6 deletions.
  1. +5 −4
  2. +1 −1 package-lock.json
  3. +1 −1 package.json
  4. +166 −0 website/versioned_docs/version-0.17.1/
  5. +115 −0 website/versioned_docs/version-0.17.1/
  6. +22 −0 website/versioned_docs/version-0.17.1/
  7. +84 −0 website/versioned_docs/version-0.17.1/
  8. +148 −0 website/versioned_docs/version-0.17.1/
  9. +35 −0 website/versioned_docs/version-0.17.1/
  10. +83 −0 website/versioned_docs/version-0.17.1/
  11. +43 −0 website/versioned_docs/version-0.17.1/
  12. +97 −0 website/versioned_docs/version-0.17.1/
  13. +136 −0 website/versioned_docs/version-0.17.1/
  14. +188 −0 website/versioned_docs/version-0.17.1/
  15. +145 −0 website/versioned_docs/version-0.17.1/
  16. +72 −0 website/versioned_docs/version-0.17.1/
  17. +52 −0 website/versioned_docs/version-0.17.1/
  18. +51 −0 website/versioned_docs/version-0.17.1/
  19. +209 −0 website/versioned_docs/version-0.17.1/
  20. +342 −0 website/versioned_docs/version-0.17.1/
  21. +164 −0 website/versioned_docs/version-0.17.1/
  22. +184 −0 website/versioned_docs/version-0.17.1/
  23. +123 −0 website/versioned_docs/version-0.17.1/
  24. +84 −0 website/versioned_docs/version-0.17.1/
  25. +172 −0 website/versioned_docs/version-0.17.1/
  26. +1 −0 website/versions.json
@@ -1,14 +1,15 @@
# Changelog and release notes

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

## v0.17.1
### Features
- add support for emitting schema file in not existing directory (#269)
- drop support for Node.js v6 (end of LTS in April 2019)
### Fixes
- fix typings discovery support for WebStorm (#276)
- allow for returning plain objects when using `ObjectType`s that implements `InterfaceType`s or extends others `ObjectType`s (#160)
### Others
- **Breaking Change**: drop support for Node.js v6 (end of LTS in April 2019)
- allow for returning plain objects when using `ObjectType`s that implements `InterfaceType`s or extends other classes (#160)

## v0.17.0
### Features

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

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

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

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

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

## How to use

First, we need to use the `@Authorized` decorator as a guard on a field, query or mutation.
Example object type field guards:

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

We can leave the `@Authorized` decorator brackets empty or we can specify the role/roles that the user needs to possess in order to get access to the field, query or mutation.
By default the roles are of type `string` but they can easily be changed as the decorator is generic - `@Authorized<number>(1, 7, 22)`.

Thus, authorized users (regardless of their roles) can only read the `publicField` or the `authorizedField` from the `MyObject` object. They will receive `null` when accessing the `hiddenField` field and will receive an error (that will propagate through the whole query tree looking for a nullable field) for the `adminField` when they don't satisfy the role constraints.

Sample query and mutation guards:

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

Authorized users (regardless of their roles) will be able to read data from the `publicQuery` and the `authedQuery` queries, but will receive an error when trying to perform the `adminMutation` when their roles don't include `ADMIN` or `MODERATOR`.

Next, we need to create our auth checker function. Its implementation may depend on our business logic:

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

The second argument of the `AuthChecker` generic type is `RoleType` - used together with the `@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 we need silent auth guards and don't want to return authorization errors to users, we can set the `authMode` property of the `buildSchema` config object to `"null"`:

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

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

## Recipes

We can also use `TypeGraphQL` with JWT authentication.
Here's an 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 we can use standard, token based authorization in the HTTP header like in classic REST APIs and take advantage of the `TypeGraphQL` authorization mechanism.

## Example

See how this works in the [simple real life example](
@@ -0,0 +1,115 @@
title: Bootstrapping
id: version-0.17.1-bootstrap
original_id: bootstrap

After creating our resolvers, type 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 with an HTTP server, WebSockets or even MQTT.

## Create Executable Schema

To create an executable schema from type and resolver definitions, we 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 resolver classes, manual imports can be cumbersome.
So we 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 an HTTP GraphQL endpoint

In most cases, the GraphQL app is served by an 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 the 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 the `apollo-server` package from npm - it's not bundled with TypeGraphQL.

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

## Create typeDefs and resolvers map

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

It accepts the same `BuildSchemaOptions` as 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 the `buildTypeDefsAndResolvers` approach because they use some low-level `graphql-js` features.
@@ -0,0 +1,22 @@
title: Browser usage
id: version-0.17.1-browser-usage
original_id: browser-usage

## Using classes in a client app

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

Since TypeGraphQL is a Node.js framework, it doesn't work in a browser environment, so we may quickly get an error, e.g. `ERROR in ./node_modules/fs.realpath/index.js`, while trying to build our app with Webpack. To correct this, we have to configure Webpack to use the decorator shim instead of the normal module. We simply add this plugin code to our webpack config:

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

Thanks to this, our bundle will be much lighter as we don't need to embed the whole TypeGraphQL library code in our app.

0 comments on commit f8b85e3

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