Git Product home page Git Product logo

graphql-zephyr's Introduction

GraphQL Zephyr

Making Postgres and GraphQL a breeze ๐ŸŒฌ๏ธ

Usage

Step 1: Specify the views that will be used by your models using plain SQL

-- views/Person.sql

SELECT
  id,
  full_name
FROM person

Here we're using a single table, but views can be queries of arbitrary complexity, including joins, subqueries, etc.

Step 2: Generate the views from the SQL files using the CLI

graphql-zephyr views/*.sql generated/views.ts

This creates a TypeScript file for you like this:

export const views = {
  Person: {
    name: "Person",
    query: `
      SELECT
        id,
        full_name
      FROM person;
    `,
    columns: {
      id: {
        kind: "integer",
      } as const,
      full_name: {
        kind: "text",
      } as const,
    },
    type: {} as { id: number; full_name: string },
  },
  // and more...
};

Step 3: Create your models

// Person.ts

import { createModel } from "graphql-zephyr";
import { views } from "../views";

export const Person = createModel({
  name: "Person",
  view: views.Person,
  fields: ({ field }) => {
    return {
      // Fields can map directly to a view column
      id: field({
        column: "id",
      }),
      // Or multiple columns
      fullName: field({
        // Note: this is an arbitrary example. In practice, you'd just return "fullName" as a column on your view.
        columns: ["first_name", "last_name"],
        // The resolver here is correctly typed based on the generated view
        resolve: ({ first_name, last_name }) => `${first_name} ${last_name}`,
        // For regular columns, the types are implied from the view columns, but here we have to specify our own
        type: "String!",
      }),
    ];
  },
});

Relationships are defined separately from models to avoid issues with circular dependencies.

// PersonRelationships.ts

import { createRelationships } from "graphql-zephyr";
import { Person } from "./Person";
import { Post } from "./Post";

export const PersonRelationships = createRelationships(({ oneToMany }) => [
  oneToMany({
    name: "posts",
    models: [Person, Post],
    // How the two models will be joined by the query builder. Each parameter here is typed based on the model's associated view columns
    join: (person, post) => sql`${person.id} = ${post.person_id}`,
  }),
]);

Step 4: Use your models to generate components for a base GraphQL schema

import { createSchemaComponents } from "graphql-zephyr";
import { Person } from "./Person";
import { PersonRelationships } from "./PersonRelationships";
import { Post } from "./Post";

const {
  typeDefs,
  resolvers,
  schema,
  createQueryBuilder,
} = await createSchemaComponents({
  models: { Person, Post },
  relationships: [...PersonRelationships],
});

This generates base type definitions and resolvers that you can build on top of when creating your schema.

type PageInfo {
  endCursor: String!
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String!
}

type PersonPostsConnection {
  edges: [PersonPostsEdge!]!
  pageInfo: PageInfo!
}

type PersonPostsEdge {
  cursor: String!
  node: Post!
}

type Person {
  id: Int!
  fullName: String!
  posts(
    after: String
    before: String
    first: Int
    last: Int
  ): PersonPostsConnection!
}

type PostLikedByConnection {
  edges: [PostLikedByEdge!]!
  pageInfo: PageInfo!
}

type PostLikedByEdge {
  cursor: String!
  node: Person!
}

type Post {
  id: Int!
  body: String!
  likedBy(
    after: String
    before: String
    first: Int
    last: Int
  ): PostLikedByConnection!
}

Note: In addition to typeDefs and resolvers, createSchemaComponents also returns a schema object. While this schema cannot be used on its own (it has no root types), it can be used with tools like GraphQL Code Generator and the GraphQL VS Code extension as shown here.

Step 5: Use the query builder inside your schema to generate complete SQL queries right from the root of your schema.

import { createPool } from "slonik";

const pool = createPool("postgres://");
const queryBuilder = createQueryBuilder(pool);

Then in your resolver:

function resolve(parent, args, ctx, info) {
  return ctx.queryBuilder.models.Person.getRelayConnection({
    info,
    where: (person) => sql`${person.full_name} ilike 'c%'`,
    orderBy: (person) => [[person.id, "DESC"]],
  });
}

The query builder will inspect your request using the info parameter and build a single database query based on it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.