Skip to content

Commit e28a028

Browse files
committed
release: 2.0.0-beta.4
1 parent 299a87d commit e28a028

25 files changed

+2944
-4
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
# Changelog and release notes
22

3-
## Unreleased
3+
<!-- ## Unreleased -->
44

55
<!-- Here goes all the unreleased changes descriptions -->
66

7+
## v2.0.0-beta.4
8+
79
### Features
810

911
- **Breaking Change**: expose shim as a package entry point `type-graphql/shim` (and `/node_modules/type-graphql/build/typings/shim.ts`)

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "type-graphql",
3-
"version": "2.0.0-beta.3",
3+
"version": "2.0.0-beta.4",
44
"private": false,
55
"description": "Create GraphQL schema and resolvers with TypeScript, using classes and decorators!",
66
"keywords": [
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
---
2+
title: Authorization
3+
id: version-2.0.0-beta.4-authorization
4+
original_id: authorization
5+
---
6+
7+
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.
8+
9+
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.
10+
11+
That's why authorization is a first-class feature in `TypeGraphQL`!
12+
13+
## How to use
14+
15+
First, we need to use the `@Authorized` decorator as a guard on a field, query or mutation.
16+
Example object type field guards:
17+
18+
```ts
19+
@ObjectType()
20+
class MyObject {
21+
@Field()
22+
publicField: string;
23+
24+
@Authorized()
25+
@Field()
26+
authorizedField: string;
27+
28+
@Authorized("ADMIN")
29+
@Field()
30+
adminField: string;
31+
32+
@Authorized(["ADMIN", "MODERATOR"])
33+
@Field({ nullable: true })
34+
hiddenField?: string;
35+
}
36+
```
37+
38+
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.
39+
By default the roles are of type `string` but they can easily be changed as the decorator is generic - `@Authorized<number>(1, 7, 22)`.
40+
41+
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.
42+
43+
Sample query and mutation guards:
44+
45+
```ts
46+
@Resolver()
47+
class MyResolver {
48+
@Query()
49+
publicQuery(): MyObject {
50+
return {
51+
publicField: "Some public data",
52+
authorizedField: "Data for logged users only",
53+
adminField: "Top secret info for admin",
54+
};
55+
}
56+
57+
@Authorized()
58+
@Query()
59+
authedQuery(): string {
60+
return "Authorized users only!";
61+
}
62+
63+
@Authorized("ADMIN", "MODERATOR")
64+
@Mutation()
65+
adminMutation(): string {
66+
return "You are an admin/moderator, you can safely drop the database ;)";
67+
}
68+
}
69+
```
70+
71+
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`.
72+
73+
Next, we need to create our auth checker function. Its implementation may depend on our business logic:
74+
75+
```ts
76+
export const customAuthChecker: AuthChecker<ContextType> = (
77+
{ root, args, context, info },
78+
roles,
79+
) => {
80+
// Read user from context
81+
// and check the user's permission against the `roles` argument
82+
// that comes from the '@Authorized' decorator, eg. ["ADMIN", "MODERATOR"]
83+
84+
return true; // or 'false' if access is denied
85+
};
86+
```
87+
88+
The second argument of the `AuthChecker` generic type is `RoleType` - used together with the `@Authorized` decorator generic type.
89+
90+
Auth checker can be also defined as a class - this way we can leverage the dependency injection mechanism:
91+
92+
```ts
93+
export class CustomAuthChecker implements AuthCheckerInterface<ContextType> {
94+
constructor(
95+
// Dependency injection
96+
private readonly userRepository: Repository<User>,
97+
) {}
98+
99+
check({ root, args, context, info }: ResolverData<ContextType>, roles: string[]) {
100+
const userId = getUserIdFromToken(context.token);
101+
// Use injected service
102+
const user = this.userRepository.getById(userId);
103+
104+
// Custom logic, e.g.:
105+
return user % 2 === 0;
106+
}
107+
}
108+
```
109+
110+
The last step is to register the function or class while building the schema:
111+
112+
```ts
113+
import { customAuthChecker } from "../auth/custom-auth-checker.ts";
114+
115+
const schema = await buildSchema({
116+
resolvers: [MyResolver],
117+
// Register the auth checking function
118+
// or defining it inline
119+
authChecker: customAuthChecker,
120+
});
121+
```
122+
123+
And it's done! 😉
124+
125+
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"`:
126+
127+
```ts
128+
const schema = await buildSchema({
129+
resolvers: ["./**/*.resolver.ts"],
130+
authChecker: customAuthChecker,
131+
authMode: "null",
132+
});
133+
```
134+
135+
It will then return `null` instead of throwing an authorization error.
136+
137+
## Recipes
138+
139+
We can also use `TypeGraphQL` with JWT authentication.
140+
Here's an example using `@apollo/server`:
141+
142+
```ts
143+
import { ApolloServer } from "@apollo/server";
144+
import { expressMiddleware } from "@apollo/server/express4";
145+
import express from "express";
146+
import jwt from "express-jwt";
147+
import bodyParser from "body-parser";
148+
import { schema } from "./graphql/schema";
149+
import { User } from "./User.type";
150+
151+
// GraphQL path
152+
const GRAPHQL_PATH = "/graphql";
153+
154+
// GraphQL context
155+
type Context = {
156+
user?: User;
157+
};
158+
159+
// Express
160+
const app = express();
161+
162+
// Apollo server
163+
const server = new ApolloServer<Context>({ schema });
164+
await server.start();
165+
166+
// Mount a JWT or other authentication middleware that is run before the GraphQL execution
167+
app.use(
168+
GRAPHQL_PATH,
169+
jwt({
170+
secret: "TypeGraphQL",
171+
credentialsRequired: false,
172+
}),
173+
);
174+
175+
// Apply GraphQL server middleware
176+
app.use(
177+
GRAPHQL_PATH,
178+
bodyParser.json(),
179+
expressMiddleware(server, {
180+
// Build context
181+
// 'req.user' comes from 'express-jwt'
182+
context: async ({ req }) => ({ user: req.user }),
183+
}),
184+
);
185+
186+
// Start server
187+
await new Promise<void>(resolve => app.listen({ port: 4000 }, resolve));
188+
console.log(`GraphQL server ready at http://localhost:4000/${GRAPHQL_PATH}`);
189+
```
190+
191+
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.
192+
193+
## Example
194+
195+
See how this works in the [simple real life example](https://github.com/MichalLytek/type-graphql/tree/v2.0.0-beta.4/examples/authorization).
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
title: AWS Lambda integration
3+
id: version-2.0.0-beta.4-aws-lambda
4+
original_id: aws-lambda
5+
---
6+
7+
## Using TypeGraphQL in AWS Lambda environment
8+
9+
AWS Lambda environment is a bit different than a standard Node.js server deployment.
10+
11+
However, the only tricky part with the setup is that we need to "cache" the built schema, to save some computing time by avoiding rebuilding the schema on every request to our lambda.
12+
13+
So all we need to do is to assign the built schema to the local variable using the `??=` conditional assignment operator.
14+
We can do the same thing for `ApolloServer`.
15+
16+
Below you you can find the full snippet for the AWS Lambda integration:
17+
18+
```ts
19+
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
20+
import { ApolloServer } from "apollo-server-lambda";
21+
22+
let cachedSchema: GraphQLSchema | null = null;
23+
let cachedServer: ApolloServer | null = null;
24+
25+
export const handler: APIGatewayProxyHandlerV2 = async (event, context, callback) => {
26+
// build TypeGraphQL executable schema only once, then read it from local "cached" variable
27+
cachedSchema ??= await buildSchema({
28+
resolvers: [RecipeResolver],
29+
});
30+
31+
// create the GraphQL server only once
32+
cachedServer ??= new ApolloServer({ schema: cachedSchema });
33+
34+
// make a handler for `aws-lambda`
35+
return cachedServer.createHandler({})(event, context, callback);
36+
};
37+
```
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
---
2+
title: Browser usage
3+
id: version-2.0.0-beta.4-browser-usage
4+
original_id: browser-usage
5+
---
6+
7+
## Using classes in a client app
8+
9+
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.
10+
11+
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` or `utils1_promisify is not a function`, 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:
12+
13+
```js
14+
module.exports = {
15+
// ... Rest of Webpack configuration
16+
plugins: [
17+
// ... Other existing plugins
18+
new webpack.NormalModuleReplacementPlugin(/type-graphql$/, resource => {
19+
resource.request = resource.request.replace(/type-graphql/, "type-graphql/shim");
20+
}),
21+
];
22+
}
23+
```
24+
25+
In case of cypress, you can adapt the same webpack config trick just by applying the [cypress-webpack-preprocessor](https://github.com/cypress-io/cypress-webpack-preprocessor) plugin.
26+
27+
However, in some TypeScript projects like the ones using Angular, which AoT compiler requires that a full `*.ts` file is provided instead of just a `*.js` and `*.d.ts` files, to use this shim we have to simply set up our TypeScript configuration in `tsconfig.json` to use this file instead of a normal TypeGraphQL module:
28+
29+
```json
30+
{
31+
"compilerOptions": {
32+
"baseUrl": ".",
33+
"paths": {
34+
"type-graphql": ["./node_modules/type-graphql/build/typings/shim.ts"]
35+
}
36+
}
37+
}
38+
```
39+
40+
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 commit comments

Comments
 (0)