1
votes

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.

1

1 Answers

-1
votes

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!]!
  }