How to make GraphQL enum data in resolver with nestjs/graphql? - enums

In this way, it can pass enum data in resolver:
enum AuthType {
GOOGLE = 'google-auth',
GITHUB = 'github-auth',
OUTLOOK = 'outlook-auth',
}
interface UsersArgs {
first: number,
from?: string,
status?: String,
authType?: AuthType,
}
export const resolvers = {
AuthType,
Query: {
users: (_record: never, args: UsersArgs, _context: never) {
// args.authType will always be 'google-auth' or 'github-auth' or 'outlook-auth'
// ...
}
}
}
There is also good example for pure GraphQL syntax as:
https://www.graphql-tools.com/docs/scalars#internal-values
In NestJS, the code like
import { Args, Query, Resolver } from '#nestjs/graphql';
import { AuthType } from '#enum/authEnum';
#Resolver()
export class AuthResolver {
constructor(private readonly authRepo: AbstractAuthSettingRepository) {}
#Query(() => AuthSetting)
findAuth(
#Args('input')
id: string,
): Promise<AuthSetting | undefined> {
return this.authRepo.findOne({ id });
}
}
How can I use AuthType in the AuthResolver class?

In order to be able to use enums in NestJS GraphQL, you need to register them once:
import { registerEnumType } from '#nestjs/graphql';
import { AuthType } from '#enum/authEnum';
registerEnumType(AuthType, { name: 'AuthType' });

Related

GraphQL - How can I tell if my delete mutation has been created?

My react, apollo, prisma, nextjs typescript app seems to think I have not made a deleteIssueGroup mutation. I think I have.
I am using:
"devDependencies": {
"#graphql-codegen/add": "3.2.1",
"#graphql-codegen/cli": "2.13.7",
"#graphql-codegen/typescript": "2.8.0",
"#graphql-codegen/typescript-operations": "2.5.5",
"#graphql-codegen/typescript-react-apollo": "3.3.5",
"#types/cookie": "0.5.1",
"#types/react": "17.0.51",
"#types/react-dom": "17.0.17",
"eslint-config-next": "12.3.1"
It's strange because I defined a deleteGroup mutation at the same time as I made the createGroup mutation and the AllGroups query, but my app thinks I don't have a deleteGroup mutation (it's right, the #generated file doesn't have it in there - except for it being listed in the list of mutations - there are no individual line items in graphql.tsx that define useDeleteIssueMutation in the same way that there are such lines for the create type). I don't know why. Is there a way to force the creation, or the recognition that there is only one of everything?
I can see in my graphql.tsx that I have:
export type MutationDeleteGroupArgs = {
id: Scalars['String'];
};
which I think means I should have the delete mutation, but in the form, when I'm trying to use it, I get an error in the terminal that says it doesn't exist.
When I run my yarn db:migrate script, it goes through the motions of running the prisma migrations (they are all up to date, but it then runs the code gen and concludes successfully).
My code is (I made a new one called IssueGroup to try and see if it was just a random unlucky twist that is causing this mess):
Prisma model
model IssueGroup {
id String #id #default(dbgenerated("gen_random_uuid()")) #db.Uuid
title String
description String
issues Issue[]
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
model
import * as Prisma from "#prisma/client"
import { Field, ObjectType } from "type-graphql"
import { BaseModel } from "../shared/base.model"
#ObjectType()
export class IssueGroup extends BaseModel implements Prisma.IssueGroup {
#Field()
title: string
#Field()
description: string
#Field(type => String)
issues: Prisma.Issue[];
}
group service:
import { prisma } from "../../lib/prisma"
import { Service } from "typedi"
import { IssueGroupInput } from "./inputs/create.input"
import { Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"
#Service()
#Resolver(() => IssueGroup)
export class IssueGroupService {
async createIssueGroup(data: IssueGroupInput) {
return await prisma.issueGroup.create({
data,
})
}
async deleteIssueGroup(id: string) {
return await prisma.issueGroup.delete({ where: { id } })
}
async updateIssueGroup(id: string, data: IssueGroupInput) {
const issueGroup = await prisma.issueGroup.findUnique({ where: { id } })
if (!issueGroup) {
throw new Error("Issue not found")
}
return await prisma.issueGroup.update({ where: { id }, data })
}
async getAllIssueGroups() {
return await (await prisma.issueGroup.findMany({orderBy: {title: 'asc'}}))
}
async getIssueGroup(id: string) {
return await prisma.issueGroup.findUnique({
where: {
id,
},
})
}
}
resolver
import { Arg, Mutation, Query, Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"
import { IssueGroupService } from "./issueGroup.service"
import { IssueGroupInput } from "./inputs/create.input"
import { Inject, Service } from "typedi"
#Service()
#Resolver(() => IssueGroup)
export default class IssueGroupResolver {
#Inject(() => IssueGroupService)
issueGroupService: IssueGroupService
#Query(() => [IssueGroup])
async issueGroups() {
return await this.issueGroupService.getAllIssueGroups()
}
#Query(() => IssueGroup)
async issueGroup(#Arg("id") id: string) {
return await this.issueGroupService.getIssueGroup(id)
}
#Mutation(() => IssueGroup)
async createIssueGroup(#Arg("data") data: IssueGroupInput) {
return await this.issueGroupService.createIssueGroup(data)
}
// : Promise<IssueGroup[]> {
#Mutation(() => IssueGroup)
async updateIssueGroup(
#Arg("id") id: string,
#Arg("data") data: IssueGroupInput
) {
return this.issueGroupService.updateIssueGroup(id, data)
}
#Mutation(() => IssueGroup)
async deleteIssueGroup(#Arg("id") id: string) {
return this.issueGroupService.deleteIssueGroup(id)
}
}
I have seen this post and can see the warning about naming queries uniquely - but I cannot see how I have offended the principle.
I have seen this post and tried following the suggestion to change my codegen.yml from:
documents:
- "src/components/**/*.{ts,tsx}"
- "src/lib/**/*.{ts,tsx}"
- "src/pages/**/*.{ts,tsx}"
to:
documents:
- "src/components/**/!(*.types).{ts,tsx}"
- "src/lib/**/!(*.types).{ts,tsx}"
- "src/pages/**/!(*.types).{ts,tsx}"
but I still get the same issue - my vsCode is suggesting I might want to use create instead of delete.

Apollo Graphql: Rename schema for backward compatibility

What I want do ?
In Apollo Graphl server, I want to change an entity Person to Human in schema but i don't want to break my clients (frontend that are querying graphql). So if client is making query for Person i want to map it to Human.
Example:
CLIENT QUERY
query {
Person {
ID
firstName
}
}
REWRITE TO
query {
Human {
ID
name
}
}
REWRITE THE RESPONSE
{
data: {
Person: {
Id: 123,
name:"abc"
}
}
}
Things that I have tried
graphql-rewriter provides something similar to what i am looking for. I went through it documentation but it doesn't have the option to rewrite the field name.
In apollo graphql documentation Apollow graphql directives, They have mentioned about rename directive but i did not find rename-directive-package the node module.
apollo-directives-package I have tried this as well but it doesn't have the option to rename the scaler field e.g
import { makeExecutableSchema } from "graphql-tools";
import { RenameDirective } from "rename-directive-package";
const typeDefs = `
type Person #rename(to: "Human") {
name: String!
currentDateMinusDateOfBirth: Int #rename(to: "age")
}`;
const schema = makeExecutableSchema({
typeDefs,
schemaDirectives: {
rename: RenameDirective
}
});
Any suggestions/help would be appreciated.
Here i hope this gives helps you, first we have to create the schema-directive
import { SchemaDirectiveVisitor } from "graphql-tools";
import { GraphQLObjectType, defaultFieldResolver } from "graphql";
/**
*
*/
export class RenameSchemaDirective extends SchemaDirectiveVisitor {
/**
*
* #param {GraphQLObjectType} obj
*/
visitObject(obj) {
const { resolve = defaultFieldResolver } = obj;
obj.name = this.args.to;
console.log(obj);
}
}
type-defs.js
directive #rename(to: String!) on OBJ
type AuthorizedUser #rename(to: "Human1") {
id: ID!
token: ID!
fullName: String!
roles: [Role!]!
}

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

How do I use graphql-type-json scalar in Nest.js code first appraoch

I've npm installed graphql-type-json and the types.
How do I use it in a code first approach, where JSONObject is the scalar in the example below.
import {Field, Int, InputType} from 'type-graphql';
import {Direction, MessageType} from '../interfaces/message.interface';
#InputType()
export class MessageInput {
#Field()
readonly to: string;
#Field()
readonly type: MessageType;
#Field()
readonly direction: Direction;
#Field()
readonly body: **JSONObject**;
}
I found this method and it worked for me. Might not be the code-first approach but I guess it would suffice until you figure it out :)
import { Field, ObjectType } from 'type-graphql';
import JSON from 'graphql-type-json';
#ObjectType()
export class YourClass {
#Field(() => JSON)
myProperty: any;
}
You can create a #Scalar() type using the approach described in the docs
It's not super elegant, but I did it by creating a #Scalar decorated class that wraps the GraphQLJSON object:
// json.scalar.ts
import { Scalar, CustomScalar } from '#nestjs/graphql';
import * as GraphQLJSON from 'graphql-type-json';
#Scalar('JSON', type => Object)
export class JsonScalar implements CustomScalar<string, any> {
name = GraphQLJSON.name;
description = GraphQLJSON.description;
serialize = GraphQLJSON.serialize;
parseValue = GraphQLJSON.parseValue;
parseLiteral = GraphQLJSON.parseLiteral;
}
Then I just added JsonScalar to the resolvers section in the module.
You can use it in a resolver with #Query(returns => Object), same goes with other places you need to specify type to nest, it's just Object
Nestjs should really allow us to add a scalar by object rather than class, surprised it's not a thing. I was switching from schema-first to code-first and ran into this issue.
Code first
npm install graphql-type-json or yarn add graphql-type-json
import { GraphQLJSON } from 'graphql-type-json';
type JSONValue =
| string
| number
| boolean
| null
| { [x: string]: JSONValue }
| Array<JSONValue>;
export class SampleModel {
#Field(() => GraphQLJSON, { nullable: true })
data?: JSONValue; // It can different e.g If you're using Prisma ORM => "Prisma.JsonValue"
}
Using schema first here, here's what works for me, on the schema:
Foo {
bar: Json
}
Custom
import { CustomScalar, Scalar } from '#nestjs/graphql';
import { Kind, ValueNode } from 'graphql';
import _ from 'lodash';
#Scalar('Json')
export class JsonScalar implements CustomScalar<string, any> {
description = 'Json custom scalar type';
parseValue(value: string): string {
this.validateFormat(value);
return value;
}
serialize(value: string): string {
return value;
}
// parseLiteral is a WIP, take it with a grain of salt
parseLiteral(ast: ValueNode): string {
if (ast.kind !== Kind.STRING) {
throw new Error(`The input value is not a string`);
}
this.validateFormat(ast.value);
return ast.value;
}
private validateFormat(input: any): void {
if (_.isNil(input) || input.constructor !== Object) throw new Error(`The input string is not in JSON format`);
}
}
and in the resolver's module:
#Module({ providers: [ JsonScalar, ...providers })
export class FooModule(){}

Nested query and mutation in type-Graphql

I found a feature in graphql to write nested query and mutation, I tried it but got null. I found the best practices of building graphqL schema on Meetup HolyJs and the speaker told that one of the best ways is building "Namespaced" mutations/queries nested, in this way you can write some middlewares inside the "Namespaced" mutations/queries and for get the Child mutation you should return an empty array because if you return an empty array, Graphql understand it and go one level deep.
Please check the example code.
Example in graphql-tools
const typeDefs = gql`
type Query { ...}
type Post { ... }
type Mutation {
likePost(id: Int!): LikePostPayload
}
type LikePostPayload {
recordId: Int
record: Post
# ✨✨✨ magic – add 'query' field with 'Query' root-type
query: Query!
}
`;
const resolvers = {
Mutation: {
likePost: async (_, { id }, context) => {
const post = await context.DB.Post.find(id);
post.like();
return {
record: post,
recordId: post.id,
query: {}, // ✨✨✨ magic - just return empty Object
};
},
}
};
This is my Code
types
import { ObjectType, Field } from "type-graphql";
import { MeTypes } from "../User/Me/Me.types";
#ObjectType()
export class MeNameSpaceTypes {
#Field()
hello: string;
#Field({ nullable: true })
meCheck: MeTypes;
}
import { Resolver, Query } from "type-graphql";
import { MeNameSpaceTypes } from "./MeNamespace.types";
#Resolver()
export class MeResolver {
#Query(() => MeNameSpaceTypes)
async Me() {
const response = {
hello: "world",
meCheck:{}
};
return response;
}
}
Result of code
query {
Me{
hello
meCheck{
meHello
}
}
}
--RESULT--
{
"data": {
"Me": {
"hello": "world",
"meCheck": {
"meHello": null
}
}
}
}
I got a null instead a meHello resolver. Where am I wrong?
Namespaced mutations are against GraphQL spec as they are not guarranted to run sequentially - more info in this discussion in GitHub issue related to your problem:
https://github.com/MichalLytek/type-graphql/issues/64

Resources