Appearance
UsersModule
The NestJS users module is a pre-built module for managing user data and interactions in a NestJS application. The module provides a set of reusable components, that can be easily integrated into a NestJS project to provide robust user management functionality. The users module includes features for creating, fetching, updating, and deleting user profiles.
Entity Inheritance
NestKit provide base classes that can be inherited and customized with your needs. For entities we use TypeORM TableInheritance
.
Key Components
The module provides a set of reusable components that can be easily integrated into a NestJS project:
User Entity
The User entity is a data schema that represents a user within your application. It typically includes fields such as the user's name, email address, password, permissions and other profile information.
Our system allows you to set custom permissions
for users. To manage permissions, we use the @deeepvision/auth library, which offers comprehensive documentation on the permissions format and access check strategy. You can refer to the library's documentation to learn more about how to define and implement custom permissions
NestJS Users Service
A UsersService provides programmatic access to the Users API. It typically includes methods for creating, retrieving, updating, and deleting user entities, as well as managing user permissions and roles.
GraphQL Users Resolver
The GraphQL UsersResolver
in NestKit provides a convenient way to retrieve and manipulate user data in a GraphQL API.
How to install UsersModule to my app
To create a UsersModule
in NestJS, you can follow these steps:
Create a
users
folder in your project'ssrc/modules
directory.Install the required dependencies for
UsersModule
:Inside the
users
folder, create auser.entity.ts
file and extendsBaseUser
from NestKit with the following code:ts// src/modules/users/user.entity.ts import { BaseUser } from '@deeepvision/nest-kit/dist/modules/users'; import { Field, ObjectType } from '@nestjs/graphql'; import { ChildEntity } from 'typeorm'; import { UserToRole } from '../user-to-roles/user-to-role.entity'; @ObjectType() @ChildEntity() export class User extends BaseUser { // ... @Field(() => [UserToRole]) userToRoles!: Promise<UserToRole[]>; }
Inside the
users
folder, create ausers.service.ts
file and extendsBaseUsersService
from NestKit with the following code:ts// src/modules/users/users.service.ts import { BaseUsersService } from '@deeepvision/nest-kit/dist/modules/users'; import { UserToRole } from '../user-to-roles/user-to-role.entity'; import { User } from './user.entity'; export class UsersService extends BaseUsersService<User, UserToRole> {}
Inside the
users
folder, create ausers.resolver.ts
file and extendsBaseUsersResolver
with the following code:ts// src/modules/users/users.resolver.ts import { BaseUsersResolver } from '@deeepvision/nest-kit/dist/modules/users'; import { Resolver } from '@nestjs/graphql'; import { Organization } from '../organizations/organization.entity'; import { User } from './user.entity'; @Resolver(() => User) export class UsersResolver extends BaseUsersResolver(User, Organization) {}
Inside the
users
folder, create ausers.module.ts
file with the following code:tsimport { Module } from '@nestjs/common'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { UsersResolver } from './users.resolver'; import { OrganizationsModule } from '../organizations/organizations.module'; import { User } from './user.entity'; import { TimezonesModule } from '../timezones/timezones.module'; import { UserToRole } from '../user-to-roles/user-to-role.entity'; import { InvitationStatusChange, InvitationStatusChangesService, USERS_SERVICE_TOKEN, } from '@deeepvision/nest-kit/dist/modules/users'; import { UserToRolesModule } from '../user-to-roles/user-to-roles.module'; @Module({ imports: [ TypeOrmModule.forFeature([User, UserToRole, InvitationStatusChange]), OrganizationsModule, TimezonesModule, UserToRolesModule, ], providers: [ UsersService, { provide: USERS_SERVICE_TOKEN, useExisting: UsersService, }, UsersResolver, InvitationStatusChangesService, ], exports: [ UsersService, { provide: USERS_SERVICE_TOKEN, useExisting: UsersService, }, InvitationStatusChangesService, ], }) export class UsersModule {}
Finally, import the UsersModule into your main AppModule or another module:
tsimport { Module } from '@nestjs/common'; import { UsersModule } from './modules/users/users.module'; @Module({ imports: [UsersModule], }) export class AppModule {}
In this code, we are importing the
UsersModule
and adding it to theimports
array of ourAppModule
.
How to create new user
Call the UsersService's create()
and pass in an object of CreateUserOptions
:
ts
const newUser = await this.usersService.create({
firstName: 'John',
lastName: 'Doe',
type: UserType.USER,
email: '[email protected]',
password: '1q2w3e4r5t6y',
avatarUrl: 'https://example.com/avatar.png',
phoneNumber: '+1 123 456 7890',
userToRoles: [
{ roleId: SystemRole.ORGANIZATION_ADMIN, organizationId: 'hcorg:xkgorjgutkfd' },
],
});
In this example, we are creating a new user with a first name, last name, email, and password. We are also setting the user's type, avatar URL, phone number and status.
The create method returns a Promise
that resolves to the newly created user object.
Create new user with GraphQL
Here's an example GraphQL mutation to create a new user
How to get user by ID
Use the getOne()
method from your UsersService
to get a user by id in other parts of your application.
ts
const user = await this.usersService.getOne('hcu:xxxxxxxxxxx');
Use the getOneOrFail()
method to retrieve a user by id or throw an error if the user is not found.
ts
const user = await this.usersService.getOneOrFail('hcu:xxxxxxxxxxx', ctx);
Fetch user by id with GraphQL
Here's an example GraphQL query to fetch user by id.
How to get user by email
Use the getOneByEmail()
method in other parts of your application to retrieve a user by their email.
ts
const user = await this.usersService.getOneByEmail('[email protected]');
Use the getOneByEmailOrFail()
method to retrieve a user by their email or throw an error if the user is not found.
ts
const user = await this.usersService.getOneByEmailOrFail('[email protected]', ctx);
Fetch user by email with GraphQL
Here's an example GraphQL query to fetch user by email.
How to get users list
Use the getMany()
method in other parts of your application to retrieve a list of users.
ts
const [users, meta] = await this.usersService.getMany({
filter: {
...
},
orderBy: UsersOrderBy.title_DESC,
});
See UsersFilter
and UsersOrderBy
for more information on how to filter and order users.
Fetch users list with GraphQL
Here's an example GraphQL query to fetch users.
How to update user
Call the update
method of the UsersService
and pass in an object of UpdateUserOptions
:
ts
const updatedUser = await this.usersService.update({
id: 'hcu:xxxxxxxxxxx',
firstName: 'Jane',
lastName: 'Doe',
email: '[email protected]',
password: 'newpassword',
avatarUrl: 'https://example.com/newavatar.png',
phoneNumber: '+1 123 456 7890',
userToRoles: [
{ role: SystemRole.ORGANIZATION_OBSERVER, organizationId: 'hcorg:xkgorjgutkfd' },
],
});
In this example, we are updating a user with an id of hcu:xxxxxxxxxxx
. We are setting the user's first name, last name, email, password, avatar URL, phone number and roles.
All fields in the upate input are optional except for the id
field.
The update
method returns a Promise
that resolves to the updated user object.
Update user with GraphQL
Here's an example GraphQL mutation to update an user
How to change user password
Call the changePassword
method of the UsersService
and pass in an object of ChangePasswordOptions
:
ts
await this.usersService.changePassword({
password: 'newpassword',
oldPassword: 'oldpassword',
userId: 'hcu:xxxxxxxxxxx',
});
In this example, we are changing the password for the user with an id of hcu:xxxxxxxxxxx
. We are setting the user's new password using the password
property, and verifying the old password using the oldPassword
property.
Change user password with GraphQL
Here's an example GraphQL mutation to change user password
How to delete user
Call the delete
method of the UsersService
and pass in the id
of the user you want to delete:
ts
await this.usersService.delete('hcu:xxxxxxxxxxx');
In this example, we are deleting a user with an id
of hcu:xxxxxxxxxxx
. The delete method returns a Promise
that resolves to void
.
Delete user with GraphQL
Here's an example GraphQL mutation to delete user
UsersService uses Soft-Delete feature
Soft delete is a feature in NestKit that allows you to mark a record as "deleted" instead of physically deleting it from the database. When you use soft delete, the record is not actually removed from the database, but a status sets to DELETED
to indicate that the record has been "soft-deleted". This allows you to retain the data and history associated with the record, while still hiding it from normal queries.