0.1.0-alpha1 • Published 5 years ago

literal-schema v0.1.0-alpha1

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

GraphQL literal schema with resolvers

npm version bundlephobia Downloads/week License coverage

Motivation

Inspired on code-first vs. schema-first discussions and styled-components which use template literals string to insert functions into css expressions, I decided to try out the same approach to bind resolver functions to a field of a definition type.

How to use

Install

npm install literal-schema

or

yarn add literal-schema

Example

Using Apollo Server

import { ApolloServer } from 'apollo-server'
import toAST from 'graphql-tag'
import { withAST } from 'schema-literal'

// (optional) Compose with graphql-tag in order to compile typeDefs to AST.
const gql = withAST(toAST)

const schema = gql`
  type Article {
    id: ID!
    title: String!

    isPublished: Boolean!
    ${({ workflow }) => workflow.some(status => status === 'public')}

    tags: [String!]!
    ${({ id }, args, context) => context.cmsApi.getTagsByContent(id)}
  }

  type User {
    id: ID!
    name: String!

    articles: [Article!]!
    ${({ id }, args, context) => context.cmsApi.getArticlesByUser(id)}
  }

  extend type Query {
    users(page: Number): [User]!
    ${(_, { page = 1 }, context) => context.cmsApi.getUsers({ page })}

    articles(page: Number): [Article]!
    ${(_, { page = 1 }, context) => context.cmsApi.getArticles({ page })}
  }
`

// `schema` has the shape `{ resolvers, typeDefs }` which is compatible with ApolloServer config object.
const server = new ApolloServer(schema)

server.listen(process.env.PORT || 3000).then(({ url }) => {
  console.log(`🚀 Server eready at ${url}`)
})

Confessions

This lib is experimental and I'm just having fun here, though it has 100% of test coverage and you could actually use it, this pattern is not tested in the wild, so be careful.

Contributions are very welcome :)

Lib created with Javali