Giter Club home page Giter Club logo

resgraph's Introduction

ResGraph

Build implementation-first GraphQL servers in ReScript, with first class Relay integration.

What it looks like

This ReScript code:

@gql.type
type query

/** A timestamp. */
@gql.scalar
type timestamp = float

/** A thing with a name. */
@gql.interface
type hasName = {@gql.field name: string}

@gql.type
type user = {
  ...hasName,
  @gql.field /** When this user was created. */ createdAt: timestamp,
  @gql.field @deprecated("Use 'name' instead") fullName: string,
}

/** Format for text. */
@gql.enum
type textFormat = Uppercase | Lowercase | Capitalized

/** The user's initials, e.g 'Alice Smith' becomes 'AS'. */
@gql.field
let initials = (user: user, ~format=Uppercase) => {
  let initials = getInitials(user.name)

  switch format {
  | Uppercase | Capitalized => initials->String.toUpperCase
  | Lowercase => initials->String.toLowerCase
  }
}

/** The current time on the server. */
@gql.field
let currentTime = (_: query): timestamp => {
  Date.now()
}

/** The currently logged in user, if any. */
@gql.field
let loggedInUser = async (_: query, ~ctx: ResGraphContext.context): option<user> => {
  switch ctx.currentUserId {
  | None => None
  | Some(userId) => await ctx.dataLoaders.userById.load(~userId)
  }
}

Generates this schema:

type Query {
  """
  The current time on the server.
  """
  currentTime: Timestamp!

  """
  The currently logged in user, if any.
  """
  loggedInUser: User
}

"""
A timestamp.
"""
scalar Timestamp

type User implements HasName {
  """
  When this user was created.
  """
  createdAt: Timestamp!
  fullName: String! @deprecated(reason: "Use 'name' instead")

  """
  The user's initials, e.g 'Alice Smith' becomes 'AS'.
  """
  initials(format: TextFormat): String!
  name: String!
}

"""
A thing with a name.
"""
interface HasName {
  name: String!
}

"""
Format for text.
"""
enum TextFormat {
  Uppercase
  Lowercase
  Capitalized
}

Check out the docs on getting started.

Introduction

ResGraph lets you build implementation first GraphQL servers, where your types and code is the source of truth for the schema.

Features

  • Query
  • Mutations
  • Subscriptions
  • Context
  • Object types
  • Input types
  • Interfaces
  • Enums
  • Unions
  • Custom scalars (including custom serializers/parsers)
  • Directives
  • Relay helpers (coming very soon)

Development notes

This is a heavy work-in-progess. The repo itself was originally forked from the ReScript editor tooling, which means that there's a ton of stuff lying around that aren't really used. This will be cleaned up later.

Local development

First, set up OCaml.

# If you haven't created the switch, do it. OPAM(https://opam.ocaml.org)
opam switch 4.14.0 # can also create local switch with opam switch create . 4.14.0

# Install dev dependencies from OPAM
opam install . --deps-only

# For IDE support, install the OCaml language server
opam install ocaml-lsp-server

Then, install JS dependencies:

npm i

Now, you can build ResGraph and run its tests:

# You might need to run this twice the first time
make test

Accompanied with the tests is a simple test server that'll let you run GraphiQL to execute operations against the test schema. Start it by running:

npm run watch-testapp

This will start the test server and watch for changes so it's restarted with any change. You can now access GraphiQL at http://localhost:9898/graphql. The test server will also dump an up to date schema.graphql on restart, so you'll be able to see how any changes you make affect the schema.

For the best experience, also run the ReScript compiler as a separate process:

npx rescript build -w

The workflow after this is setup is roughly:

  1. Make changes to the test schema (primarily located in Schema.res)
  2. Run ResGraph via make test
  3. Test the changes in GraphiQL, or see them in schema.graphql

High level overview of how ResGraph works

  1. You write your types and code in ReScript, and annotate them with attributes to expose them via GraphQL.
  2. ResGraph runs after the ReScript compiler has recompiled, and scans your project for all GraphQL-related things. It then extracts all relevant GraphQL things from the compiled type information.
  3. What it finds is then transformed into an actual graphql-js schema that you can run.

ResGraph is fast, because it's leveraging the standard ReScript tooling, and using OCaml.

Acknowledgements

This is a spiritual sibling project to Grats, from which this project derives most of its ideas, reimplemented in the ReScript ecosystem instead.

resgraph's People

Contributors

cometkim avatar zth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

resgraph's Issues

M1 binary

Either build and commit to repo for each change, or wait for GH runners to support building them.

Document and examplify Node interface

Would be nice to have a good set of examples for how to implement the Node interface, which is 1st class in ResGraph. Preferably with a few helpers for creating good, short, URL friendly ID:s. cc @cometkim (message pack etc)

Clean up unused OCaml code

There's an absolute ton of unused OCaml code since I started out by copying the entire editor tooling repo. Most will be possible to clean out.

Type creators?

This is about as magical as I dare make something, but imagine this (pageInfo definition omitted):

@gql.type type user = {name: string}

@gql.typeCreator
type edge<'node> = {
  @gql.field cursor: option<string>,
  @gql.field node: option<'node>,
}

@gql.typeCreator
type connection<'edge> = {
  @gql.field pageInfo: pageInfo,
  @gq.field edges: option<array<option<edge>>>,
}

@gql.type
type userEdge = edge<user>

@gql.type
type userConnection = connection<userEdge>

Generating this:

type User {
  name: String!
}

type UserEdge {
  cursor: String
  node: User
}

type UserConnection {
  pageInfo: PageInfo!
  edges: [UserEdge]
}

Essentially allowing records to act as "templates" which you can generate types from, that would then also leverage any instantiated type parameters.

Would solve for example making good connection helpers, and allow you to write functions operating on connection<'node> directly.

Example is for connections, but can probably be generalized.

Improve interface type codegen

  1. Split codegenned types for interfaces into separate files
  2. Ensure inference can work as intended by moving one of the generated types into a sub module (they're very similar, so type inference clashes for them)

Input unions?

Something sorely missing from GraphQL is input unions. While we won't extend the GraphQL language ourselves, we could potentially implement input unions server side:

@gql.inputUnion
type timePeriod = Preset({datePreset: datePreset}) | Dates({from: timestamp, to: timestamp})

@gql.field
let data = (_: query, ~timePeriod) => {
  getDataByTimePeriod(timePeriod)
}
type Query {
  data(datePreset: DatePreset, from: Timestamp, to: Timestamp): DataForPeriod
}

We'd have a code generated layer in each resolver using a input union that automatically throws if the argument configuration isn't correct.

Unclear error message when __generated__ folder is missing

If the folder defined in resgraph.json doesn't exist, ResGraph fails to compile.

This is the error message if /src/schema/__generated__ doesn't exist:

Error: Command failed: /path/to/repo/node_modules/resgraph/bin/darwin/resgraph.exe generate-schema
  /path/to/repo/src  /path/to/repo/src/schema/__generated__ true

This error could be a common mistake for new users and the message could be improved

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.