Schema Stitching resolve conflict by adding prefix

So I have this two schemas

So I have this two schemas

Schema1

type Permission {
    relation: Relation
}

enum Relation {
ONE
TWO
THREE
}

Schema2

type Permission {
relation: Relation
}

enum Relation {
FOUR
FIVE
SIX
}

The expect result is something similar to: (but I'm open to different ideas) The queries I would like to make after the merge are:

{
permissions{
relation
}
}

And get a result like

"permissions": [
{
"relation": "ONE"
},
{
"relation": "SIX"
}
]

or

"permissions": [
{
"relation": "schema1ONE"
},
{
"relation": "schema2SIX"
}
]

And mutations like:

mutation{
createPermission(
relation: ONE
){
relation
}
}

mutation{
createPermission(
relation: SIX
){
relation
}
}

or

mutation{
createPermission(
relation: schema1ONE
){
relation
}
}

mutation{
createPermission(
relation: schema2SIX
){
relation
}
}

I'm trying using the transformSchema function on graphql-tools but can't quite figure it out correctly:

const Schema1 = await getRemoteSchema('schema1_url', 'schema1');
const Schema2 = await getRemoteSchema('schema2_url', 'schema2');

const schemas = [Schema1, Schema2]

const schema = mergeSchemas({
schemas: schemas,
resolvers: {}
});

getRemoteSchema definition

export const getRemoteSchema = async (uri: string, schemaName: string): Promise<GraphQLSchema> => {
const httpLink = new HttpLink({ uri, fetch });

const schema = await introspectSchema(httpLink);

const executableSchema = makeRemoteExecutableSchema({
schema,
httpLink,
});

// transform schema by renaming root fields and types
const renamedSchema = transformSchema(
executableSchema,
[
new RenameTypes(name => {
if (name == 'Relation') {
return schemaName + name
} else {
return name
}
}),
// new RenameRootFields((operation, name) => ${schemaName}_${name})
]
);

return renamedSchema;
}

I made this glitch https://glitch.com/edit/#!/schema-stitching-conflict So it's easier to see the problem.

Fully functional WhatsApp Clone using Angular, GraphQL, Apollo, TypeScript and PostgreSQL

Fully functional WhatsApp Clone using Angular, GraphQL, Apollo, TypeScript and PostgreSQL

An open-source full-stack example app made with Angular 7.2, TypeScript, GraphQL Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM.

An open-source full-stack example app made with Angular 7.2, TypeScript, GraphQL Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM.

You might have seen it around already — an open-source WhatsApp Clone tutorial; a project which was originally started in 2015 by Urigo based on Angular-Meteor and Ionic, and have been throughout different incarnations ever since.

You may have also noticed that we recently published a new React version of the Whatsapp Clone tutorial.

This time around, I’m happy to announce that a new version of the WhatsApp Clone is here, and it’s based on Angular 7.2, Angular CLI 7.3.2, Material-UI, TypeScript, Apollo, GraphQL-Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM, full with step by step guides to teach you every step of the way.

Click me to go to the tutorial page

We’re back in business!

What is it good for?

This app was built with all the latest and hottest technologies out there. The purpose is simple — it should be a guideline for building a proper app, thus we thought very carefully about the design patterns and architecture used in it, plus, we made sure to cover all communication methods with a GraphQL-back-end in different variations (query, mutation, subscription). This way whenever you’re looking to start a new app, maintain an existing one or upgrade your dev-stack, the WhatsApp-clone can be a great source to start with! It’s full stack and has a complete flow.

Why did we choose this dev-stack?

Angular, GraphQL, Apollo, PostgreSQL and TypeScript for obvious reasons — they are backed by a strong ecosystem that grows rapidly. These technologies can be used in endless variations, and there’s no one way which is the most right of doing so, but we chose a way that makes the most sense for us and that we truly believe in when it comes to building apps. We’ve connected it all with TypeORM, GraphQL-Code-Generator, GraphQL-Modules for the following reasons:

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

What to expect?

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

The tutorial goes through every aspect of building the app, starting from the very basics. We will start building a very simple server with a fake db, then we will introduce Authentication, Subscriptions, a real database backed by PostgreSQL and TypeORM plus advanced tooling like GraphQL Code Generator and GraphQL Modules.

This can be extremely useful for those who have little to no background in one of the technologies in our dev-stack.

What’s next?

Right now we implemented a simple REST-based Passport authentication, but we already have PRs[1][2] for Accounts-JS based authentication which will use the GraphQL endpoint instead of traditional REST ones. An additional chapter about Pagination is also expected, as well as a “Performance” chapter tackling the N+1 problem with GraphQL. Our backend has been designed to handle way more features than the ones currently implemented, so be ready because features like the Whatsapp blue ticks are going to land on our clone very soon.

Keep up to date

This tutorial was written using Tortilla — the Tutorial framework.

This means that we will keep upgrading the tutorial with the latest versions of Angular and the other libraries, and instead of doing the same tutorial all over again, you will get a git-diff of how to upgrade the existing tutorial! We care about your time as a developer.

Influence

We want to hear your opinions!

Should we choose another library and technology over another? Could we write the code better/cleaner? Should we add a specific feature to the app? We want to hear it all!

Please tell us now so we could integrate your feedback on the tutorial itself!

We keep evolving the stack and as the tutorial is based on git commits, we can create the same clone with different tech-stacks and compare them on this real app using code diffs.

Soon we will also release yet another version of the Whatsapp Clone, using Ionic, Stencil and Web Components.

If you are good at creating screencast and videos, we would love your help in creating videos for some of the chapters.

Everything is completely free and open source, and we want your help and (not financial) contribution!

Best place would be to open an issue or create a PR on the repositories:

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

Again, all types of feedback is welcome, write freely!

Thanks for reading ❤

Need Help in apollo-graphql

hi sir, I am Abhijeet from India. I just started working on graphql.I am trying to set reminder in apollo-graphql and I have no idea how it works in apollo. I am doing only backend graphql (nodejs) . help me for set a reminder in backend using apollo-graphql. This is urgent for me to create my new project.

hi sir, I am Abhijeet from India. I just started working on graphql.I am trying to set reminder in apollo-graphql and I have no idea how it works in apollo. I am doing only backend graphql (nodejs) . help me for set a reminder in backend using apollo-graphql. This is urgent for me to create my new project.

Getting started with GraphQL and TypeScript

Getting started with GraphQL and TypeScript

In this tutorial, I’ll be showing you how to use TypeScript with GraphQL using TypeGraphQL.

TypeScript is a superset of JavaScript, and its adoption has skyrocketed in recent years, as many apps are now being rewritten in it. If you have ever created a GraphQL server with TypeScript, then you would know it’s not as straightforward as in the JavaScript counterpart.


Prerequisites

This tutorial assumes the following:

  • Node.js and NPM installed on your computer
  • Basic knowledge of GraphQL
  • Basic knowledge of TypeScript
  • TypeScript installed on your computer, which you can get from the official website
What’s TypeGraphQL?

TypeGraphQL is a framework building GraphQL APIs in Node.js. It makes use of TypeScript classes and decorators for defining GraphQL schema and types as well as resolvers. With TypeGraphQL, we don’t need to manually define types in SDL or create interfaces for our GraphQL schema. TypeGraphQL allows us to have only one source of truth, that way reducing field type mismatches, typos etc.

Another interesting thing about TypeGraphQL is how well it integrates with decorator-based libraries, like TypeORM, sequelize-typescript or Typegoose. This allows us to define both the GraphQL type and the entity in a single class, so we don’t need to edit multiple files to add or rename some properties.


Getting started

To get started with TypeGraphQL, we need to first install it along with its dependencies. We’ll start by creating a new project:

    $ mkdir graphql-typescript
    $ cd graphql-typescript
    $ npm init -y

Then we install TypeGraphQL:

    $ npm install type-graphql

Next, we need to install TypeScript as a dev-dependency as well as types for Node.js:

    $ npm install typescript @types/node --save-dev

TypeGraphQL requires the reflect-metadata shim, so we need to install that as well:

    $ npm install reflect-metadata

Next, we need to define some TypeScript configurations for our project. Create a tsconfig.json file within the project’s root directory, and paste the snippet below into it:

    // tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "lib": ["dom", "es2016", "esnext.asynciterable"],
    "moduleResolution": "node",
    "outDir": "./dist",
    "strict": true,
    "strictPropertyInitialization": false,
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/**/*"]
}

If you have ever worked with TypeScript before (which this tutorial assumes), then you should be familiar with some of the settings above. Since TypeGraphQL makes extensive use of decorators, which are an experimental feature of TypeScript, we need to set both emitDecoratorMetadata and experimentalDecorators as true. Also, we need to add esnext.asynciterable to the list of library files, since graphql-subscription uses AsyncIterator.


Defining the GraphQL schema

We can start defining the schema for our GraphQL server. Create a new src directory, then within it, create a new schemas directory. Inside the schemas directory, create a Project.ts file and add the following code in it:

    // src/schemas/Project.ts

import { Field, Int, ObjectType } from "type-graphql";
import Task from "./Task";

@ObjectType()
export default class Project {
  @Field(type =&gt; Int)
  id: number;

  @Field()
  name: string;

  @Field(type =&gt; [Task])
  tasks: Task[];
}

We define a Project class and use the @ObjectType() decorator to define it as a GraphQL type. The Project type has three fields: id, name and tasks. We use the @Field decorator to define these fields. The @Field decorator can also accept optional arguments. We can pass to it the type the field should be or an object containing other options we want for the field. We explicitly set the type of the id field to be Int while tasks is an array of the type Task (which we’ll create shortly).

Next, let’s define the schema for the Task type. Inside the schemas directory, create a Task.ts file and add the following code in it:

    // src/schemas/Task.ts

import { Field, Int, ObjectType } from "type-graphql";
import Project from "./Project";

@ObjectType()
export default class Task {
  @Field(type =&gt; Int)
  id: number;

  @Field()
  title: string;

  @Field(type =&gt; Project)
  project: Project;

  @Field()
  completed: boolean;
}

This is pretty similar to the Project schema. With our schema defined, we can move on to creating the resolvers.


Adding sample data

Before we get to the resolvers, let’s quickly define some sample data we’ll be using to test out our GraphQL server. Create a data.ts file directly inside the src directory, and paste the snippet below into it:

    // src/data.ts

export interface ProjectData {
  id: number;
  name: string;
}

export interface TaskData {
  id: number;
  title: string;
  completed: boolean;
  project_id: number;
}

export const projects: ProjectData[] = [
  { id: 1, name: "Learn React Native" },
  { id: 2, name: "Workout" },
];

export const tasks: TaskData[] = [
  { id: 1, title: "Install Node", completed: true, project_id: 1 },
  { id: 2, title: "Install React Native CLI:", completed: false, project_id: 1},
  { id: 3, title: "Install Xcode", completed: false, project_id: 1 },
  { id: 4, title: "Morning Jog", completed: true, project_id: 2 },
  { id: 5, title: "Visit the gym", completed: false, project_id: 2 },
];

Creating the resolvers

Create a new resolvers directory inside the src directory. Inside the resolvers directory, create a ProjectResolver.ts file and paste the code below in it:

    // src/resolvers/ProjectResolver.ts

import { Arg, FieldResolver, Query, Resolver, Root } from "type-graphql";
import { projects, tasks, ProjectData } from "../data";
import Project from "../schemas/Project";

@Resolver(of =&gt; Project)
export default class {
  @Query(returns =&gt; Project, { nullable: true })
  projectByName(@Arg("name") name: string): ProjectData | undefined {
    return projects.find(project =&gt; project.name === name);
  }

  @FieldResolver()
  tasks(@Root() projectData: ProjectData) {
    return tasks.filter(task =&gt; {
      return task.project_id === projectData.id;
    });
  }
}

We use the @Resolver() decorator to define the class as a resolver, then pass to the decorator that we want it to be of the Project type. Then we create our first query, which is projectByName, using the @Query() decorator. The @Query decorator accepts two arguments: the return type of the query and an object containing other options which we want for the query. In our case, we want the query to return a Project and it can return null as well. The projectByName query accepts a single argument (name of the project), which we can get using the @Arg decorator. Then we use find() on the projects array to find a project by its name and simply return it.

Since the Project type has a tasks field, which is a custom field, we need to tell GraphQL how to resolve the field. We can do that using the @FieldResolver() decorator. We are getting the object that contains the result returned from the root or parent field (which will be the project in this case) using the @Root() decorator.

In the same vein, let’s create the resolvers for the Task type. Inside the resolvers directory, create a TaskResolver.ts file and paste the code below in it:

    // src/resolvers/TaskResolver.ts

import { Arg, FieldResolver, Mutation, Query, Resolver, Root } from "type-graphql";
import { projects, tasks, TaskData } from "../data";
import Task from "../schemas/Task";

@Resolver(of =&gt; Task)
export default class {
  @Query(returns =&gt; [Task])
  fetchTasks(): TaskData[] {
    return tasks;
  }

  @Query(returns =&gt; Task, { nullable: true })
  getTask(@Arg("id") id: number): TaskData | undefined {
    return tasks.find(task =&gt; task.id === id);
  }

  @Mutation(returns =&gt; Task)
  markAsCompleted(@Arg("taskId") taskId: number): TaskData {
    const task = tasks.find(task =&gt; {
      return task.id === taskId;
    });
    if (!task) {
      throw new Error(`Couldn't find the task with id ${taskId}`);
    }
    if (task.completed === true) {
      throw new Error(`Task with id ${taskId} is already completed`);
    }
    task.completed = true;
    return task;
  }

  @FieldResolver()
  project(@Root() taskData: TaskData) {
    return projects.find(project =&gt; {
      return project.id === taskData.project_id;
    });
  }
}

We define two queries: fetchTasks and getTask. The fetchTasks simply returns an array of all the tasks that have been created. The getTask query is pretty similar to the projectByName query. Then we define a mutation for marking a task as completed, using the @Mutation. This mutation will also return a Task. Firstly, we get the task that matches the supplied taskId. If we can’t find a match, we simply throw an appropriate error. If the task has already been marked as completed, again, we throw an appropriate error. Otherwise, we set the task completed value to true and lastly return the task.

Just as we did with the Project type, we define how we want to resolve the project field.


Building the GraphQL server

With everything in place, all that is left now is to tie them together by building a GraphQL server. We will be using graphql-yoga for building our GraphQL server. First, let’s install it:

    $ npm install graphql-yoga

With that installed, create an index.ts file directly inside the src directory, and paste the code below in it:

    // src/index.ts

import { GraphQLServer } from "graphql-yoga";
import "reflect-metadata";
import { buildSchema } from "type-graphql";
import ProjectResolver from "./resolvers/ProjectResolver";
import TaskResolver from "./resolvers/TaskResolver";

async function bootstrap() {
  const schema = await buildSchema({
    resolvers: [ProjectResolver, TaskResolver],
    emitSchemaFile: true,
  });

  const server = new GraphQLServer({
    schema,
  });

  server.start(() =&gt; console.log("Server is running on http://localhost:4000"));
}

bootstrap();

Since we need to build our schema first before making use of it in our GraphQL server, we create an async function, which we call bootstrap() (you can name it however you like). Using the buildSchema() from type-graphql, we pass to it our resolvers and we set emitSchemaFile to true (more on this shortly). Once the schema has been built, we instantiate a new GraphQL server and pass to it the schema. Then we start the server. Lastly, we call bootstrap().

Sometimes, we might need to see or inspect the schema in SDL (Schema Definition Language) that TypeGraphQL will generate for us. One way we can achieve that is setting emitSchemaFile to true at the point of building the schema. This will generate a schema.gql file directly in project’s root directory. Of course, we can customize the path however we want.

Note: make sure to import reflect-metadata on top of your entry file (before you use/import type-graphql or your resolvers)
Testing it out

Before we start testing our GraphQL, we need to first compile our TypeScript files to JavaScript. For that, we’ll be using the TypeScript compiler. Running the command below directly from the project’s root directory:

    $ tsc

The compiled JavaScript files will be inside the dist directory, as specified in tsconfig.json. Now we can start the GraphQL server:

    $ node ./dist/index.js

The server should be running on http://localhost:4000, and we can test it out with the following query:

    # fetch all tasks

{
  fetchTasks {
    title
    project {
      name
    }
  }
}


Conclusion

In this tutorial, we looked at what is TypeGraphQL and it makes it easy to work with GraphQL and TypeScript. To learn more about TypeGraphQL and other advanced features it provides, do check out their official website as well as the GitHub repo.

The complete code for this tutorial is available on GitHub.


Learn More

Secure Node.js, Express.js and PostgreSQL API using Passport.js

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Full Stack Developers: Everything You Need to Know

Machine Learning In Node.js With TensorFlow.js

Build a Simple Web App with Express, Angular, and GraphQL

Build a Basic App with Spring Boot and JPA using PostgreSQL

The Complete Python & PostgreSQL Developer Course

SQL & Database Design A-Z™: Learn MS SQL Server + PostgreSQL

The Complete SQL Bootcamp

Originally published by Chimezie Enyinnaya at https://pusher.com