Navigate back to the homepage

User Registration with a NestJS GraphQL Server and Prisma

Aryan Jabbari
January 13th, 2020 · 3 min read

User Registration with a NestJS GraphQL Server and Prisma

Phew, it’s been a while. Let’s get back to creating our NestJS server leveraging the power of GraphQL and Prisma.

By the end of this article, you’ll be able to create a GraphQL registration resolver using Prisma and NestJS. This resolver will be responsible for creating a user with an encrypted password on your Prisma backend.

First, we’ll add the User model to Prisma. Then, we’ll write a resolver for the createUser mutation that will create a user in Prisma.

I also created a YouTube video that covers this material if you’d rather watch a video.

This article will not cover login and permissions. That’ll be done in a later article.

Let’s get started!

Disclaimer

If this is the first post you are reading from my NestJS, GraphQL and Prisma series, I suggest you go on back and read Stand Up a Node.js Server with NestJS including TypeScript and GraphQL and Use Prisma with a NestJS GraphQL Server.

If reading just isn’t your thing, you can also catch up on YouTube.

Add User Model to Prisma

By the end of this section, you should have a User model in Prisma.

To add the user model to Prisma, open your /datamodel.prisma file. We’ll keep the user model simple.

1type User {
2 id: Int! @id
3 email: String!
4 password: String!
5}

Your /datamodel.prisma should therefore look like this:

1type Message {
2 id: Int! @id
3 description: String!
4}
5
6type User {
7 id: Int! @id
8 email: String!
9 password: String!
10}

Now, deploy the new model to Prisma (which will add the User model to the database).

1prisma deploy

Then, generate the GraphQL schema:

1graphql get-schema

and lastly generate the Typescript Prisma binding:

1graphql codegen

If you don’t have the packages above installed, go back to “Defining Our Data Model and Deploying” in the last article to learn the correct packages to download and go into more detail on the above three scripts.

Open up the Prisma console with:

1prisma console

then open up the Prisma service that corresponds with this tutorial.

You should see a new User model there in the console:

User Model in Prisma

Great. You can delete the Prisma generated code (now in the /generated directory) as it won’t be of any use to us. git commit your code and learn to create users with GraphQL and Prisma.

Create a New User with Email Address and Password

With our User ready to be created in the database and our code binding, we are ready to dive into some code. First, create a NestJS user module, user service and user resolver:

1nest g module users
2nest g service users
3nest g resolver users

The first thing we need to do is inject the Prisma service into our User service. To do that, we’ll first need to import the PrismaModule in the user module. Open src/users/users.module.ts and import the PrismaModule:

1// src/users/users.module.ts
2import { Module } from '@nestjs/common';
3import { UsersService } from './users.service';
4import { PrismaModule } from 'src/prisma/prisma.module';
5
6@Module({
7 imports: [PrismaModule],
8 providers: [UsersService],
9})
10export class UsersModule {}

With the PrismaModule imported, we can inject it into our User service. Open src/users/users.service.ts and inject the PrismaModule:

1import { Injectable } from '@nestjs/common';
2import { PrismaService } from 'src/prisma/prisma.service';
3
4@Injectable()
5export class UsersService {
6 constructor(private readonly prisma: PrismaService) {}
7}

Now we’re ready to create our createUser service function. This function accept an email and password and:

  1. Encrypt the password using bcrypt.
  2. Send the username and password to the Prisma server (which will in turn save the data to the database).
  3. Return the newly created user.

As noted in number 1, we will use bcrypt for our password encryption. Let’s install the package and its corresponding types:

1npm install bcrypt
2npm install @types/bcrypt --save-dev
3# or
4yarn add bcrypt
5yarn add -D @types/bcrypt

The createUser function should be added to src/users/users.service.ts as follows:

1import { Injectable } from '@nestjs/common';
2import * as bcrypt from 'bcrypt';
3import { PrismaService } from 'src/prisma/prisma.service';
4
5@Injectable()
6export class UsersService {
7 constructor(private readonly prisma: PrismaService) {}
8
9 async createUser(email: string, password: string) {
10 // remove any case sensitivity from our email address
11 const lowerCaseEmail = email.toLowerCase();
12 // hash the password
13 const hashedPassword = await bcrypt.hash(password, 10);
14 // sabe the user
15 const user = this.prisma.mutation.createUser({
16 data: {
17 email: lowerCaseEmail,
18 password: hashedPassword,
19 },
20 });
21 // return the newly saved user
22 return user;
23 }
24}

Perfect, now let’s use this service in our User resolver to write the createUser mutation. With the createUser function in our User /service/ doing most of the heavy lifting, the resolver is as easy as calling the service and returning the user. In src/users/users.resolver.ts:

1import { Resolver, Mutation, Args } from '@nestjs/graphql';
2import { UsersService } from './users.service';
3
4@Resolver('Users')
5export class UsersResolver {
6 constructor(private readonly users: UsersService) {}
7
8 @Mutation()
9 async createUser(
10 @Args('data')
11 data: {
12 email: string;
13 password: string;
14 }
15 ) {
16 const user = await this.users.createUser(data.email, data.password);
17 return user;
18 }
19}

Use GraphQL Playground to Create Users

With all the code in place, we can use the GraphQL Playground to create new users. Run your development NestJS server with:

1npm run start:dev
2# OR
3yarn start:dev

After it’s finished starting up, go to http://localhost:3000/graphql and run the following mutation:

1mutation {
2 createUser(data: { email: "test@test.com", password: "test" }) {
3 id
4 email
5 password
6 }
7}

Your GraphQL playground should return a newly created user!

User Mutation in GraphQL Playground

Create a few new users as we’ll need it in my next post where we cover login.

Conclusion

With that, you now have a NestJS server with GraphQL and Prisma that allows for user registration.

If at any point you got lost in this tutorial, please refer to this tutorial’s code on Github. It should contain everything you need to catch up.

📧 Join my email list and get notified about new content

Stay updated with all my blog posts and future randomness!

More articles from The WebDev Coach

Getting Started with the GitHub Package Registry

Getting Started with the GitHub Package Registry What is GitHub Package Registry? Like npm , the GitHub Package Registry hosts software…

January 1st, 2020 · 2 min read

Use Prisma with a NestJS GraphQL Server

Use Prisma with a NestJS GraphQL Server Before We Get Started In my last blog post , I described how to stand up a Node.js server with…

October 5th, 2019 · 4 min read
© 2018–2020 The WebDev Coach
Link to $https://twitter.com/aryanjabbariLink to $https://www.youtube.com/c/thewebdevcoachLink to $https://dev.to/aryanjnycLink to $https://github.com/AryanJ-NYCLink to $https://www.linkedin.com/in/aryanjabbariLink to $https://www.instagram.com/thewebdevcoach/