literal-schema

0.1.0-alpha1 • Public • Published

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

Package Sidebar

Install

npm i literal-schema

Weekly Downloads

1

Version

0.1.0-alpha1

License

MIT

Unpacked Size

11.4 kB

Total Files

6

Last publish

Collaborators

  • sebas5384