Node Server Tutorial - Part 2: Project Graph
Run the command: npx nx graph
. A browser should open up with the following contents:
You'll notice that there is no dependency drawn from products-api
to the auth
library. The project graph is derived from the source code of your workspace. Once we actually wire everything up, the project graph will update accordingly.
auth
Update the contents of the generated auth.ts
file:
1export type AuthResponse = AuthSuccessResponse | AuthFailureResponse;
2export interface AuthSuccessResponse {
3 success: true;
4 name: string;
5}
6export interface AuthFailureResponse {
7 success: false;
8}
9
10export function doAuth(): AuthResponse {
11 return { success: true, name: 'Cheddar' };
12}
13
products-api
Add a post endpoint to the main.ts
file of the root project that uses the doAuth()
function.
1import express from 'express';
2import { doAuth } from 'auth';
3
4const host = process.env.HOST ?? 'localhost';
5const port = process.env.PORT ? Number(process.env.PORT) : 3000;
6
7const app = express();
8
9app.get('/', (req, res) => {
10 res.send({ message: 'Hello API' });
11});
12
13app.post('/auth', (req, res) => {
14 res.send(doAuth());
15});
16
17app.listen(port, host, () => {
18 console.log(`[ ready ] http://${host}:${port}`);
19});
20
When a library is created, Nx adds a new Typescript path to the tsconfig.base.json
file. The running Typescript server process inside of your editor sometimes doesn't pick up these changes and you have to restart the server to remove inline errors on your import statements. This can be done in VS Code from the command palette when viewing a typescript file (Command-Shift-P) "Typescript: Restart TS server"
e2e
Update the e2e tests to check the new /auth
endpoint.
1import axios from 'axios';
2
3describe('GET /', () => {
4 it('should return a message', async () => {
5 const res = await axios.get(`/`);
6
7 expect(res.status).toBe(200);
8 expect(res.data).toEqual({ message: 'Hello API' });
9 });
10});
11
12describe('POST /auth', () => {
13 it('should return a status and a name', async () => {
14 const res = await axios.post(`/auth`, {});
15
16 expect(res.status).toBe(200);
17 expect(res.data).toEqual({ success: true, name: 'Cheddar' });
18 });
19});
20
Now run npx nx graph
again:
The graph now shows the dependency between products-api
and auth
.
The project graph is more than just a visualization - Nx provides tooling to optimize your task-running and even automate your CI based on this graph. This will be covered in more detail in: 4: Task Pipelines.
What's Next
- Continue to 3: Task Running