๐ป Lab 9 - Generate a type lib that the API and frontend can share
May 31, 2023 ยท View on GitHub
โฐ Estimated time: 15 minutes
Now our project graph looks a bit disconnected. The frontend and the API still do not have anything in common. The power of Nx libraries is that they can be shared among any number of projects.
We'll look at creating libs to store Typescript interfaces and then we'll use the Nx Move generator to move that library around our project, with minimal effort.
๐ Learning outcomes:
- Explore other real-world examples of creating shared libs for a specific project
- Learn to use the
movegenerator
๐ฒ After this workshop, you should have:
App Screenshot
No change in how the app looks!File structure
๐๏ธโโ๏ธ Steps:
-
Stop serving both the API and the frontend
-
Generate a new
@nx/jslib calledutil-interfaceinside thelibs/apifolder.โ ๏ธ It's important that we create it in the
/apifolder for now -
Create your
Gameinterface: seelibs/api/util-interface/src/lib/api-util-interface.ts -
Import it in the API service:
apps/api/src/app/app.service.tsโ ๏ธ You might need to restart the Typescript compiler in your editor
๐ณ Hint
import { Game } from '@bg-hoard/api/util-interface'; const games: Game[] = [...];
-
Build the API and make sure there are no errors
๐ณ Hint
nx build api
-
Inspect the project graph
-
Make sure to commit everything before proceeding!
Our frontend store makes calls to the API via the HttpClient service:
this.http.get<any>(`/api/games/${id}`);
But it's currently typed to any - so our component has no idea about the shape of the objects it'll get back!
Let's fix that - we already have a Game interface in a lib. But it's nested in the api folder - we need to move it out to the root libs/ folder so any project can use it!
-
Use the
@nx/workspace:movegenerator to move the interface lib created above into the root/libsfolderโ ๏ธ Make sure you use the
--dry-runflag until you're confident your command is correct๐ณ Hint 1
๐ณ Hint 2
Use the
--helpcommand to figure out how to target a specific project Alternatively, check out the docs๐ณ Hint 3
Your library name is
api-util-interface- to move it to root, its new name needs to beutil-interface
-
We can now import it in the frontend components and use it when making the
httprequest:๐ณ Hint
Frontend store shell app:
apps/store/src/app/app.component.tsimport { Game } from '@bg-hoard/util-interface'; this.http.get<Game[]>('/api/games');
Routed game detail component:
libs/store/feature-game-detail/src/lib/game-detail/game-detail.component.tsthis.http.get<Game>(`/api/games/${id}`);โ ๏ธ Open
apps/api/src/app/app.service.ts. Notice how we didn't have to update the imports in the API. Themovegenerator took care of that for us! -
Trigger a build of both the store and the API projects and make sure it passes
-
Inspect the project graph
-
Inspect what changed from the last time you committed, then commit your changes
๐If you get stuck, check out the solution