Skip to content

GraphQL Backend

Sahil Bhatia edited this page Apr 20, 2020 · 9 revisions

GraphQL endpoint: "/v1/graphql"

Each each entity, GraphQL backend is expected to expose all attributes and relationships.

For each foreign key, expose a method with same name (without "_id"), which exposes the associated object.

For each "1-M" relationship, expose a pluralized method named after the related entity. It should return an array of objects.

Fot enums stored as "int", expose a method that return enum mapping.

In case for any entity, a custom method is required, it shall be explicity mentioned in corresponding github issue.

**NOTE: ** Each attribute in GraphQL needs to have:

  • data type defined
  • marked as required or optional

GraphQL Backend implementation requires 2 essential things:

  1. Schema Definition Language (or SDL)
  2. Resolvers
    2.1. Query (Read only queries)
    2.2. Mutation (handles create, update, delete)

Example 1)

const { ApolloServer, gql } = require('apollo-server');

// Hardcoded data store
const books = [
  {
    title: 'Harry Potter and the Chamber of Secrets',
    author: 'J.K. Rowling',
  },
  {
    title: 'Jurassic Park',
    author: 'Michael Crichton',
  },
];

// Schema definition
const typeDefs = gql`
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

// Resolver map
const resolvers = {
  Query: {
    books() {
      return books;
    }
  },
};

// Pass schema definition and resolvers to the
// ApolloServer constructor
const server = new ApolloServer({ typeDefs, resolvers });

// Launch the server
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

Example 2) For "users"

Step 1) Schema would be:

type User {
  org_id: ID,
  org: Organization,
  name: String,
  email: String,
  display_name: String,
  profile_image_url: String,
  status: UserStatus,
  role_id: ID,
  role: Role,
  timezone: String,
  hi_5_quota_balance: Int,
  created_on: String,
  updated_on: String,
  updated_by: User,  `
}
enum UserStatus {
  Activated,
  Deactivated
}
type Organization {
  id: ID,
  name: String,
  contact_email: String,
  domain_name: String,
  subscription_status: SubscriptionStatus,
  subscription_valid_upto: String,
  hi_5_limit: Int,
  hi_5_quota_renewal_frequency: QuotaRenewalFrequency
}
enum QuotaRenewalFrequency {
  ...
}  `
enum SubscriptionStatus {
  ...
}
type Query {
  users: [User],
  organizations: [Organization]
}
type Mutation {
  // "!" at the end of data type means, mandatory
  insert_user(org_id: ID!, name: String!, email: String!, ...): User
}

Step 2) Define resolver

const resolvers = {
  Query: {
    users(parent, args, context, info) {
      return users; # list of users queried from db or another endpoint.
    }
  }
}
Clone this wiki locally