Prisma / Graphql resolver - graphql

Good morning all,
I m currently back in the famous world of web development and I have in mind to develop a tool by using Nest/Prisma/Graphl.
However, I'm struggling a little bit on key element like the following one.
Basically, I can see that, by using the "include" function in Prisma (module.service.ts), I'm getting subModules list: this is the expected behavior.
However, on Graphl side, to cover field resolver (module.resolver.ts), I can see that the same request is executing again to cover SubModules field.....
What am I missing?????
See below the code:
module.module.ts
import { Field, ID, ObjectType } from '#nestjs/graphql'
import { SubModule } from './submodule.model'
#ObjectType()
export class Module {
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Field((type) => ID)
id: number
name: string
description: string
icon: string
active: boolean
position: number
subModules?: SubModule[]
}
submodule.model.ts
import { Field, ObjectType, ID } from '#nestjs/graphql';
import { Module } from './module.model';
#ObjectType()
export class SubModule {
#Field((type) => ID)
id: number;
name: string;
description: string;
icon: string;
active: boolean;
position: number;
module: Module;
}
module.resolver.ts
import {
Resolver,
Query,
ResolveField,
Parent,
Args,
InputType,
} from '#nestjs/graphql'
import { Module } from 'src/models/module.model'
import { ModuleService } from './module.service'
import { SubModuleService } from './sub-module.service'
#InputType()
class FilterModules {
name?: string
description?: string
icon?: string
active?: boolean
}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Resolver((of) => Module)
export class ModuleResolver {
constructor(
private moduleService: ModuleService,
private subModuleService: SubModuleService,
) {}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Query((returns) => Module)
async module(#Args('ModuleId') id: number) {
return this.moduleService.module(id)
}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Query((returns) => [Module], { nullable: true })
async modules(
#Args({ name: 'skip', defaultValue: 0, nullable: true }) skip: number,
#Args({ name: 'filterModules', defaultValue: '', nullable: true })
filterModules: FilterModules,
) {
return this.moduleService.modules({
skip,
where: {
name: {
contains: filterModules.name,
},
},
})
}
#ResolveField()
async subModules(#Parent() module: Module) {
const { id } = module
return this.subModuleService.subModules({ where: { moduleId: id } })
}
}
module.service.ts
import { Injectable } from '#nestjs/common'
import { PrismaService } from 'src/prisma.service'
import { Prisma, Module } from '#prisma/client'
#Injectable()
export class ModuleService {
constructor(private prisma: PrismaService) {
prisma.$on<any>('query', (event: Prisma.QueryEvent) => {
console.log('Query: ' + event.query)
console.log('Params' + event.params)
console.log('Duration: ' + event.duration + 'ms')
})
}
async module(id: number): Promise<Module | null> {
return this.prisma.module.findUnique({
where: {
id: id || undefined,
},
})
}
async modules(params: {
skip?: number
take?: number
cursor?: Prisma.ModuleWhereUniqueInput
where?: Prisma.ModuleWhereInput
orderBy?: Prisma.ModuleOrderByWithRelationInput
}): Promise<Module[]> {
const { skip, take, cursor, where, orderBy } = params
return this.prisma.module.findMany({
skip,
take,
cursor,
where,
orderBy,
})
}
async updateModule(params: {
where: Prisma.ModuleWhereUniqueInput
data: Prisma.ModuleUpdateInput
}): Promise<Module> {
const { where, data } = params
return this.prisma.module.update({
data,
where,
})
}
}
Thanks in advance for your help

Related

Setup & configure NestJS 9 (TypeORM 0.3+) to use custom repositories

I am currently attempting to update my project to the latest version of NestJS and TypeORM and I am having a great deal of difficulty wrapping my head around how to setup the project so that I can use custom repositories in a similar way that it was before.
The biggest problem is that #EntityRepository and .getCustomRepository have been deprecated. I have been pouring over documentation and I can't seem to figure out the new way of doing things.
From the TypeORM docs, it says to do something like this:
export const UserRepository = dataSource.getRepository(User).extend({
findByName(firstName: string, lastName: string) {
return this.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName })
.andWhere("user.lastName = :lastName", { lastName })
.getMany()
},
})
ok... I get that... use the dataSource to create the repo and extend it with the additional functions. Seem's easy enough, right?
WRONG!
You can't create the repo until the dataSource object is created. In straight up TypeORM you can create your new DataSource but in nest, it's an async bootstrap... which means when you import your repo/service files the data source isn't yet there.
grrr.
So, here is my code (simplified).
Basically, it's a small app with users. The users have a role. So you can get the user by name, or update the user name so long as it has a role. If the role is null, then you can't do it. (the create method is not included, assume it's there)
app.config.ts
// database values and such are loaded from an env file. (not included)
export const applicationModuleConfig: ApplicationModuleConfig = {
typeOrmConfig: {
type: "postgres",
host,
username,
database,
port,
synchronize: false,
cache: true,
entities: [resolve(__dirname, "./**/*.entity.ts"), resolve(__dirname, "./**/*.entity.js")],
migrations: [resolve(__dirname, "./migrations/**/*{.ts,.js}")],
migrationsTableName: "migrations",
migrationsRun: true,
password,
}
}
users.entity.ts (trimmed, assume there are more fields/columns)
#Entity()
#ObjectType("Users")
export class Users {
#Field(() => Int)
#PrimaryGeneratedColumn()
id: number;
#Field()
#Column({ type: "varchar", nullable: false, default: "" })
name: string;
#Field()
#Column({ type: "varchar", nullable: false, default: "" })
role: string;
}
users.repository.ts
export const UsersRepository = dataSource.getRepository(Users).extend({
findByName(name: string) {
return this.createQueryBuilder("users")
.where("users.name = :name", { name })
.getOne()
},
async verifyRole(id: number) {
const user = await this.createQueryBuilder("users")
.where("users.id = :id", { id })
.getOne()
return user?.role !== null;
},
})
users.service.ts
#Injectable()
export class UsersService {
constructor(private readOnly usersRepo: UsersRepository) {}
findByName(name: string) {
return this.usersRepo.findByName(name);
}
verifyRole(id: number) {
return this.usersRepo.verifyRole(id);
}
}
users.resolver.ts
#Resolver(() => User)
#UseGuards(GraphqlAuthGuard, PermissionsGuard, ScopeGuard)
export class UserResolver {
constructor(private readonly usersService: UsersService) {}
#Query(() => User, { name: "user" })
async getUser(
#Args({
name: "name",
type: () => String,
})
name: string,
#CurrentUser() currentUser: AuthorizedUser,
): Promise<Users> {
return this.usersService.findByName(name);
}
// assume EditUsersInput is a object matching the entity fields.
#Mutation(() => Users)
#VerifyUser<{ input: EditUsersInput }>(({ input }) => {
// >>> this doesn't work <<<*
return UsersRepository.verifyRole(input.id);
})
async editUser(
#Args(
{
name: "input",
type: () => EditUsersInput,
},
new ValidationPipe(),
)
input: EditUsersInput,
): Promise<Users> {
await UsersRepository.editUser(input); // assume the editUser method exists in the service and repo.
return UsersRepository.findByUserId(input.id); // assume the findByUserId method exists in the service and repo.
}
app.module.ts (I will admit I am not sure what I am supposed to be doing in this file)
#Global()
#Module({
imports: [TypeOrmModule.forFeature([...entitiesWithoutAModuleHere])],
providers: [UsersService, UsersRepository],
exports: [UsersService, UsersRepository],
})
export class ApplicationModule {
static forRoot(config: ApplicationModuleConfig): DynamicModule {
const {
graphql,
typeOrmConfig,
numConcurrentReportJobs,
redis: { tls: redisTls, ...redisRest },
} = config;
////
// a bunch of redis code goes in here...
////
return {
module: ApplicationModule,
imports: [
// omitted unrelated imports, such as bullQueue and stuff like that.
TypeOrmModule.forRoot({
...typeOrmConfig,
}),
GraphQLModule.forRoot(graphql),
ConfigurationModule.forRoot(config), // I am not sure if this file is important or not, but I am omitting it for now.
],
};
}
constructor(public dataSource: DataSource) {
// AH HA! The dataSource has been initialized by nest!
// but, the repository errors have already occurred and it never got this far.
// I don't know what to do here.
}
}
main.ts
import blah from "blah";
import { applicationModuleConfig } from "./app.config";
import everythingElse from "otherStuff";
import { ApplicationModule } from "./app.module"; // <-- KaBOOM!
async function bootstrap() {
initializeTransactionalContext();
patchTypeORMRepositoryWithBaseRepository();
const ApplicationModule = require("./app.module");
const app = await NestFactory.create(ApplicationModule.forRoot(applicationModuleConfig), { bodyParser: false });
app.use(
session({
resave: false, //As per https://github.com/expressjs/session#resave
saveUninitialized: false,
store: new (require("connect-pg-simple")(session))({
createTableIfMissing: true,
}),
secret: process.env.APP_SESSION_SECRET, cookie: { secure: secureCookies },
}),
);
await app.listen(3000);
}
bootstrap().then(() => null);
I know I am doing it wrong, but I can't figure out how to do it right. Any thoughts, comments, suggestions, examples, tutorials, or explanations of the right way?
Thanks!

Schema must contain uniquely named types named "Project"

I am creating a Apollo Graphql backend using type-orm. I create an entity called Project:
import { Field, ObjectType } from "type-graphql";
import { BaseEntity, Column, Entity, ObjectID, ObjectIdColumn } from "typeorm";
#ObjectType()
#Entity()
export class Project extends BaseEntity {
#Field(() => String)
#ObjectIdColumn()
id: ObjectID;
#Field()
#Column({ unique: true })
name!: string;
#Field()
#Column()
startDate!: Date;
#Field()
#Column({nullable: true})
endDate!: Date
#Field()
#Column({unique:true})
githubUrl: string;
}
and the resolver project:
import { Arg, Mutation, Query, Resolver } from 'type-graphql'
import {Project} from '../entities/project'
import {ProjectInput, ProjectResponse} from '../types/ProjectTypes'
#Resolver()
export class ProjectResolver {
#Query(() => [Project])
async getProjects(): Promise<Project[] | null> {
let projects = await Project.getRepository().find();
return projects;
}
#Mutation(() => ProjectResponse)
async createProject(
#Arg("input") input: ProjectInput
): Promise<ProjectResponse>{
let project : Project;
if(input.name == ""){
throw Error("Invalid input")
}
try{
project = await Project.create({
name: input.name,
startDate: input.startDate,
}).save();
}catch (error) {
if (error.code === 11000) {
return {
errors: [
{
field: "project",
message: "The project name is already in use",
},
],
};
} else return error;
}
return {project: project};
}
#Mutation(() => ProjectResponse)
async setProjectEndDate(
#Arg("projectId") projectId: string,
#Arg("endDate") endDate: Date
): Promise<ProjectResponse>{
let project = await Project.getRepository().findOne(projectId)
if(project){
if(project?.startDate > endDate){
return {
errors:[{
field:"EndDate",
message:"The end date must be a date after the start date of a project."
}]
}
}
project.endDate = endDate;
project.save();
}
return {
errors:[{
field:"Project",
message:"Project could not be found."
}]
}
}
}
this is the code of the 2 auxiliary classes for the input and response of the resolver:
#InputType()
export class ProjectInput{
#Field()
name: string
#Field()
startDate: Date
#Field(()=> Date,{nullable:true})
endDate?: Date | null
#Field(()=> String, {nullable:true})
githubUrl?: string
}
#ObjectType()
export class ProjectResponse{
#Field(() => [FieldError], { nullable: true })
errors?: FieldError[]
#Field(() => Project, { nullable: true })
project?: Project | null
}
this is the code I use to create the ApolloServer object:
const apolloServer = new ApolloServer({
introspection: true,
playground: true,
schema: await buildSchema({
resolvers: [ProjectResolver],
validate: false, // Disable default GraphQL errors
}),
context: ({ req, res }) => ({ req, res}), // Enables use of context (with request) in resolvers
})
And the error I get is the following:
Error: Schema must contain uniquely named types but contains multiple types named "Project".
at new GraphQLSchema (C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\node_modules\graphql\type\schema.js:194:15)
at Function.generateFromMetadataSync (C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\node_modules\type-graphql\dist\schema\schema-generator.js:31:32)
at Function.generateFromMetadata (C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\node_modules\type-graphql\dist\schema\schema-generator.js:16:29)
at Object.buildSchema (C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\node_modules\type-graphql\dist\utils\buildSchema.js:10:61)
at C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\dist\index.js:42:38
at Generator.next ()
at fulfilled (C:\Users\User\Desktop\UPV\Proyectos\Cv web\myweb-backend\dist\index.js:5:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
I don't know what the problem is so I would appreciate your help
I have managed to solve the problem by changing the import of the class 'Project' made in the 'ProjectResolver' class.
Instead of:
import {Project} from '../entities/project'
Now looks like this:
import {Project} from '../../src/entities/project'

TypeGraphql - #inputtype on typeorm

Hello I need to check if there is an email in the database already:
with this:
return User.findOne({ where: { email } }).then((user) => {
if (user) return false;
return true;
});
I have the following inputtypes:
#InputType()
export class RegisterInput {
#Field()
#IsEmail({}, { message: 'Invalid email' })
email: string;
#Field()
#Length(1, 255)
name: string;
#Field()
password: string;
}
I would like to know if there is any way for me to validate the email in the inputtype? or just in my resolve:
#Mutation(() => User)
async register(
#Arg('data')
{ email, name, password }: RegisterInput,
): Promise<User> {
const hashedPassword = await bcrypt.hash(password, 12);
const user = await User.create({
email,
name,
password: hashedPassword,
}).save();
return user;
}
Actually you can register your own decorator for class-validator
For example it can look something like this:
isEmailAlreadyExists.ts
import {
registerDecorator,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import { UserRepo } from '../../repositories/UserRepo';
import { InjectRepository } from 'typeorm-typedi-extensions';
#ValidatorConstraint({ async: true })
export class isEmailAlreadyExist
implements ValidatorConstraintInterface {
#InjectRepository()
private readonly userRepo: UserRepo;
async validate(email: string) {
const user = await this.userRepo.findOne({ where: { email } });
if (user) return false;
return true;
}
}
export function IsEmailAlreadyExist(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [],
validator: isEmailAlreadyExist,
});
};
}
If you're injecting dependencies than you should in inject it in class-validator too. Simply add to your main file this:
import { Container } from 'typedi';
import * as classValidator from 'class-validator';
classValidator.useContainer(Container);
...
const schema = await buildSchema({
resolvers: [...],
container: Container,
});
Then you can use decorator in your InputType
import { InputType, Field } from 'type-graphql';
import { IsEmailAlreadyExist } from '../../../utils/validators/isEmailAlreadyExist';
#InputType()
export class YourInput {
#Field()
#IsEmailAlreadyExist()
email: string;
}
I actually just figured this out myself for my own project.
You can simply add a validation on the email from RegisterInput argument and throw an error if the email already exists.
import { Repository } from 'typeorm'
import { InjectRepository } from 'typeorm-typedi-extensions'
...
// Use dependency injection in the resolver's constructor
constructor(
#InjectRepository(User) private readonly userRepository: Repository<User>
) {}
...
// Your mutation
#Mutation(() => User)
async register(
#Arg('data')
{ email, name, password }: RegisterInput,
): Promise<User> {
const hashedPassword = await bcrypt.hash(password, 12);
const userWithEmail = this.userRepository.find({ email: email })
// If a user with the email was found
if (userWithEmail) {
throw new Error('A user with that email already exists!')
}
const user = await User.create({
email,
name,
password: hashedPassword,
}).save();
return user;
}
To use the InjectRepository make sure you add a "container" to your buildSchema function:
import { Container } from 'typedi'
...
const schema = await buildSchema({
resolvers: [...],
container: Container
})
Let me know if this works out for you? Thanks!

Nest Error: Cannot determine GraphQL output type for getProducts

I get this error when i try to return a custom dto from a resolver. (node:28156) UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for getProducts
Here is what my code looks like.
product.entity.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
BaseEntity,
BeforeInsert,
} from 'typeorm';
import { ObjectType, Field, ID, Float, Int } from '#nestjs/graphql';
#ObjectType()
#Entity()
export class Product extends BaseEntity {
#Field(() => ID)
#PrimaryGeneratedColumn('uuid')
id: string;
#Column({ default: '', select: false })
ratingsString: string;
#Field(() => [Int])
ratings;
#BeforeInsert()
setRatingsString() {
this.ratingsString = this.ratings.join(',');
}
}
product.resolver.ts
import { Resolver, Query, Args, ResolveField, Int, Parent } from '#nestjs/graphql';
import { Product } from './product.entity';
import { ProductService } from './product.service';
#Resolver(() => Product)
export class ProductResolver {
constructor(private productService: ProductService) {}
#Query(() => GetProductDto, { name: 'products' })
async getProducts(#Args() page: number) {
return this.productService.getProducts(page);
}
}
product.service.ts
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './product.entity';
import { GetProductDto } from './product.dto';
#Injectable()
export class ProductService {
constructor(
#InjectRepository(Product) private productRepo: Repository<Product>,
) {}
async getProducts(page: number): Promise<GetProductDto> {
const MAX_PRODUCT_PER_PAGE = 20;
const start = page < 1 ? 1 : page;
const [products, productsCount] = await this.productRepo.findAndCount({
skip: (start - 1) * MAX_PRODUCT_PER_PAGE,
take: MAX_PRODUCT_PER_PAGE,
});
const productList = products.map(product => {
product.ratings = product.ratingsString.split(',').map(Number);
delete product.ratingsString;
return product;
});
return {
products: productList,
total: productsCount,
};
}
}
product.dto.ts
import { Field, Int, InputType } from '#nestjs/graphql';
import { Product } from './product.entity';
#InputType()
export class GetProductDto {
#Field(() => [Product])
products: Product[];
#Field(() => Int)
total: number;
}
The expectation here is that when i call the products query i will recieve an object with products and total. Whee products will be my array of products. What am I doing wrong?
Turns out all I needed was to provide a argument to Args.
#Query(() => GetProductDto, { name: 'products' })
async getProducts(#Args('arg_the_client_will_it_with') page: number) {
return this.productService.getProducts(page);
}

GraphQL endpoint return null object in Nest.js

I'm using Nest.js and Sequelize-Typescript to build a GraphQL API.
When I called delete and update mutations I got a null object, but the operation it is done. I need to put {nullable: true} because I got a error saying Cannot return null for non-nullable field . How I fix it? I need the endpoint to return the updated object to show the information on the front
error img
book.dto.ts
import { ObjectType, Field, Int, ID } from 'type-graphql';
#ObjectType()
export class BookType {
#Field(() => ID, {nullable: true})
readonly id: number;
#Field({nullable: true})
readonly title: string;
#Field({nullable: true})
readonly author: string;
}
book.resolver.ts
import {Args, Mutation, Query, Resolver} from '#nestjs/graphql';
import { Book } from './model/book.entity';
import { BookType } from './dto/book.dto';
import { CreateBookInput } from './input/createBook.input';
import { UpdateBookInput } from './input/updateBook.input';
import { BookService } from './book.service';
#Resolver('Book')
export class BookResolver {
constructor(private readonly bookService: BookService) {}
#Query(() => [BookType])
async getAll(): Promise<BookType[]> {
return await this.bookService.findAll();
}
#Query(() => BookType)
async getOne(#Args('id') id: number) {
return await this.bookService.find(id);
}
#Mutation(() => BookType)
async createItem(#Args('input') input: CreateBookInput): Promise<Book> {
const book = new Book();
book.author = input.author;
book.title = input.title;
return await this.bookService.create(book);
}
#Mutation(() => BookType)
async updateItem(
#Args('input') input: UpdateBookInput): Promise<[number, Book[]]> {
return await this.bookService.update(input);
}
#Mutation(() => BookType)
async deleteItem(#Args('id') id: number) {
return await this.bookService.delete(id);
}
#Query(() => String)
async hello() {
return 'hello';
}
}
book.service.ts
import {Inject, Injectable} from '#nestjs/common';
import {InjectRepository} from '#nestjs/typeorm';
import {Book} from './model/book.entity';
import {DeleteResult, InsertResult, Repository, UpdateResult} from 'typeorm';
#Injectable()
export class BookService {
constructor(#Inject('BOOKS_REPOSITORY') private readonly bookRepository: typeof Book) {}
findAll(): Promise<Book[]> {
return this.bookRepository.findAll<Book>();
}
find(id): Promise<Book> {
return this.bookRepository.findOne({where: {id}});
}
create(data): Promise<Book> {
return data.save();
}
update(data): Promise<[number, Book[]]> {
return this.bookRepository.update<Book>(data, { where: {id: data.id} });
}
delete(id): Promise<number> {
return this.bookRepository.destroy({where: {id}});
}
}
You can fix it setting option parameter in the resolver query
#Query(() => BookType, { nullable: true })
Why would you want to return those fields from a delete? You must already have them on your front end... you could just change the return type of that mutation to true or false based on whether it worked or not... and in the update you could do the mutation and add returning: true in your options if you are using postgres... if not then don't return the result of the update, do the update and return the result of findOne or findById whichever is applicable

Resources