Reader small image

You're reading from  Angular for Enterprise Applications - Third Edition

Product typeBook
Published inJan 2024
Reading LevelExpert
PublisherPackt
ISBN-139781805127123
Edition3rd Edition
Languages
Right arrow
Author (1)
Doguhan Uluca
Doguhan Uluca
author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca

Right arrow

Working with REST and GraphQL APIs

In Chapter 1, Angular’s Architecture and Concepts, I introduced you to the wider architecture in which web applications exist, and in Chapter 3, Architecting an Enterprise App, we discussed various performance bottlenecks that can impact the success of your app. However, your web app can only perform as well as your full-stack architecture performs. If you’re working with an inadequate API design or a slow database, you will spend your time implementing band-aid solutions instead of addressing the root cause of the issues. The moment we move away from the minimalist mindset and start patching holes, we are on our way to constructing a fragile tower that is at risk of collapsing or very expensive to maintain. In short, the choices made in full-stack architecture can profoundly impact the success of your web application. You and your team simply cannot afford to be ignorant of how APIs are designed. Often, the correct way to implement...

Technical requirements

The most up-to-date versions of the sample code for the book can be found on GitHub at the following linked repository. The repository contains the final and completed state of the code. This chapter requires the Docker Desktop and Postman applications.

It is critical that you get lemon-mart-server up and running on your development environment and have lemon-mart communicate with it. Refer to the instructions documented here or in the README on GitHub to get your server up and running.

For server-side implementation in Chapter 7:

  • Clone the lemon-mart-server repository using the --recurse-submodules option:
    git clone --recurse-submodules https://github.com/duluca/lemon-mart-server
    
  • In the VS Code terminal, execute cd web-app; git checkout master to ensure the submodule from https://github.com/duluca/lemon-mart is on the master branch.

    Later, in the Git submodules section, you can configure the web...

Full-stack architecture

Full-stack refers to the entire stack of software that makes an application work, from databases to servers, APIs, and the web and/or mobile apps that leverage them. The mythical full-stack developer is all-knowing and can comfortably operate in all verticals of the profession. It is next to impossible to specialize in all things software-related and to be considered an expert in every given topic. However, to be considered an expert in a single topic, you must also be well-versed in related topics. When learning about a new topic, it is very helpful to keep your tooling and language consistent to absorb new information without additional noise.

For these reasons, I opted to introduce you to the MEAN stack, rather than Spring Boot using Java or ASP.NET using C#. By sticking to familiar tools and languages such as TypeScript, VS Code, npm, GitHub, Jasmine/Jest, Docker, and CircleCI, you can better understand how a full-stack implementation comes together...

Working with monorepos

A monorepo (monolithic repository) is a software development strategy to host code from multiple projects in a single repository. This allows for unified versioning, simplified dependency management, and easier code sharing across projects. In a monorepo, developers can jump between projects within the same IDE window and reference code more easily across projects, such as sharing TypeScript interfaces between the frontend and the backend, ensuring that data objects line up every time.

You can enable access to multiple projects in the same IDE window using multi-root workspaces in VS Code, where you can add multiple projects to display in the Explorer window. However, a monorepo combines projects at the source control level, allowing us to build them together on our CI server. Read more about multi-root workspaces at https://code.visualstudio.com/docs/editor/multi-root-workspaces.

Having access to code from multiple projects makes it possible...

Designing APIs

In Chapter 3, Architecting an Enterprise App, I cover the importance of a stateless, data-driven design as part of Router-first architecture. As part of this goal, I highlight identifying major data entities that your app will operate around as an important activity. It’s no mistake that API design also greatly benefits by designing around major data entities.

In full-stack development, nailing down the API design early on is important. If your frontend and backend teams can agree on major data entities and the shape of those entities, then both teams can agree on a contract to go off and build their own respective pieces of software. In Router-first architecture, I highlight the importance of leveraging TypeScript interfaces to quickly stub out the architecture of your app. Backend teams can conduct similar activities.

A little bit of early design work and agreement ensures integration between these components can be established very early on, and with...

Implementing APIs with Express.js

Let’s go over the architecture and file structure of our backend so that we get an understanding of how the server is bootstrapped, how routing is configured for API endpoints, how public resources are served, and how services are configured.

Review the file structure of our Express server:

server/src
├── api.ts
├── app.ts
├── config.ts
├── docs-config.ts
├── graphql
│   ├── api.graphql.ts
│   ├── helpers.ts
│   └── resolvers.ts
├── index.ts
├── models
│   ├── enums.ts
│   ├── phone.ts
│   └── user.ts
├── public
├── services
│   ├── authService.ts
│...

MongoDB ODM with DocumentTS

DocumentTS acts as an ODM, implementing a layer of models to enable rich and customizable interaction with database objects. ODM is the document-based database equivalent of an Object Relational Mapper (ORM) in relational databases. Think of Hibernate or Entity Framework. If you’re not familiar with these concepts, I recommend that you do further research before moving on.

To get started, you can check out the following article, MongoDB ORMs, ODMs, and Libraries, at https://www.mongodb.com/developer/products/mongodb/mongodb-orms-odms-libraries.

At its core, DocumentTS leverages the Node.js driver for MongoDB. The makers of MongoDB implement this driver. It guarantees the best performance and feature parity with new MongoDB releases, whereas third-party libraries often lag in supporting new features. By using the database.getDbInstance method, you can access the native driver directly. Otherwise, you will access Mongo through the...

Implementing JWT auth

In Chapter 5, Designing Authentication and Authorization, we discussed implementing a JWT-based authentication mechanism. In LemonMart, you implemented a base auth service that can be extended for custom authentication services.

We’ll leverage three packages for our implementation:

  • jsonwebtoken: Used to create and encode JWTs
  • bcryptjs: Used to hash and salt a user’s password before saving it in the database, so we never store a user’s password in plain text
  • uuid: A generated universally unique identifier that is useful when resetting a user’s password to a random value

A hash function is a consistently repeatable, one-way encryption method, which means you get the same output every time you provide the same input, but even if you have access to the hashed value, you cannot readily figure out what information it stores. We can, however, compare whether the user has entered the correct password...

Custom server auth provider

Now that you understand the auth implementation in our server, we can implement a custom auth provider in LemonMart, as covered in Chapter 6, Implementing Role-Based Navigation:

You must implement this custom auth provider in your Angular app.

The code sample for this section is in the projects/stage10 folder in the lemon-mart-app app or web-app folder.

  1. Start by creating a baseUrl variable in environment.ts so that we can connect to your server.
  2. In environment.ts and environment.prod.ts, implement a baseUrl variable.
  3. Also, select authMode as AuthMode.CustomServer:
    web-app/src/environments/environment.ts
    web-app/src/environments/environment.prod.ts
    export const environment = {
      ...
      baseUrl: 'http://localhost:3000',
      authMode: AuthMode.CustomServer,
    
  4. Install a helper library to programmatically access TypeScript enum values:
    $ npm i ts-enum-util
    
  5. ...

Summary

In this chapter, we covered full-stack architecture. You learned about building a minimal MEAN stack. You now know how to create a monorepo for a full-stack application and configure a Node.js server with TypeScript. You learned about monorepos, containerizing a Node.js server, and declaratively defining infrastructure with Docker Compose. Using Docker Compose with CircleCI, we saw how you can verify your infrastructure in a CI environment.

You learned how to design a RESTful API using OpenAPI and GraphQL using Apollo, set up an Express.js app, and configure it such that you can generate interactive documentation for your APIs. You learned about the benefits of using DocumentTS with MongoDB.

You then implemented a JWT-based authentication service with an authenticate middleware to secure API endpoints and allow for RBAC. Finally, you implemented two custom authentication providers in Angular. For REST, we used HttpClient, and for GraphQL, Apollo Client.

The next...

Exercise

You secured your endpoints using the authenticate middleware. You configured Postman to send a valid token so that you can communicate with your secured endpoints. By way of an exercise, try removing the authenticate middleware and calling the same endpoint with and without a valid token. Re-add the middleware, and then try the same thing again. Observe the different responses you get from the server.

Further reading

Questions

Answer the following questions to ensure you’ve understood the key concepts from this chapter without googling anything. Do you know if you got all the answers right? Visit https://angularforenterprise.com/self-assessment for more:

  1. What are the main components that make for a great developer experience?
  2. What is a .env file?
  3. What is the purpose of the authenticate middleware?
  4. How does Docker Compose differ from using the Dockerfile?
  5. What is an ODM? How does it differ from an ORM?
  6. What is middleware?
  7. What are the uses of the OpenAPI spec?
  8. How would you refactor code for the /v2/users/{id} PUT endpoint in userRouter.ts so that the code is reusable?
  9. What are the major differentiators between REST and GraphQL?
  10. What are the similarities between OpenAPI and the GraphQL schema?

Join our community on Discord

Join our community’s Discord space for discussions with the authors and other readers...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Angular for Enterprise Applications - Third Edition
Published in: Jan 2024Publisher: PacktISBN-13: 9781805127123
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca