All Projects → capaj → decapi

capaj / decapi

Licence: MIT license
Create GraphQL API by decorating TypeScript classes

Projects that are alternatives of or similar to decapi

Type Graphql
Create GraphQL schema and resolvers with TypeScript, using classes and decorators!
Stars: ✭ 6,864 (+8374.07%)
Mutual labels:  schema, decorators, gql
soap-typescript
SOAP decorators for creating wsdl's and annotating services to provide metadata for node-soap
Stars: ✭ 20 (-75.31%)
Mutual labels:  schema, decorators
xml-core
xml-core is a set of classes that make it easier to work with XML within the browser and node.
Stars: ✭ 18 (-77.78%)
Mutual labels:  schema, decorators
Typegql
Create GraphQL schema with TypeScript classes.
Stars: ✭ 415 (+412.35%)
Mutual labels:  schema, decorators
gql
This is a GraphQL server written in Go
Stars: ✭ 31 (-61.73%)
Mutual labels:  schema, gql
Joiful
TypeScript Declarative Validation for Joi
Stars: ✭ 177 (+118.52%)
Mutual labels:  schema, decorators
Truss
Assertions API for Clojure/Script
Stars: ✭ 239 (+195.06%)
Mutual labels:  schema
another-json-schema
Another JSON Schema validator, simple & flexible & intuitive.
Stars: ✭ 48 (-40.74%)
Mutual labels:  schema
Soqlx
SoqlXplorer is an awesome tool for developers using the Salesforce.com platform.
Stars: ✭ 220 (+171.6%)
Mutual labels:  schema
Schematics
Project documentation: https://schematics.readthedocs.io/en/latest/
Stars: ✭ 2,461 (+2938.27%)
Mutual labels:  schema
schema-and-structured-data-for-wp
Creating the best Structured Data and Schema plugin for WordPress
Stars: ✭ 66 (-18.52%)
Mutual labels:  schema
vue-class-state
面向对象风格的vue状态管理
Stars: ✭ 14 (-82.72%)
Mutual labels:  decorators
mobivoc
A vocabulary for future-oriented mobility solutions and value-added services supporting them.
Stars: ✭ 27 (-66.67%)
Mutual labels:  schema
Graphql Rover
🚀 GraphQL + Vue.js + D3.js schema viewer, powered by introspection.
Stars: ✭ 239 (+195.06%)
Mutual labels:  schema
NoSQLDataEngineering
NoSQL Data Engineering
Stars: ✭ 25 (-69.14%)
Mutual labels:  schema
Password Validator
Validates password according to flexible and intuitive specification
Stars: ✭ 224 (+176.54%)
Mutual labels:  schema
graphql-docker-api
A GraphQL Server for the Docker API
Stars: ✭ 57 (-29.63%)
Mutual labels:  schema
Codemeta
Minimal metadata schemas for science software and code, in JSON-LD
Stars: ✭ 218 (+169.14%)
Mutual labels:  schema
Vue Form Json Schema
Create forms using JSON schema. Bring your components!
Stars: ✭ 253 (+212.35%)
Mutual labels:  schema
pony-capnp
Cap’n Proto plugin for generating serializable Pony classes. 🐴 - 🎩'n 🅿️
Stars: ✭ 19 (-76.54%)
Mutual labels:  schema

npm version deps codecov Build Status

What is decapi?

demo

decapi is a set of decorators for creating GraphQL APIs in typescript. Write your types and GQL schema at once killing two birds with one stone.

decapitation

Examples:

Basic example

Example below is able to resolve such query

query {
  hello(name: "Bob") # will resolve to 'Hello, Bob!'
}
import { SchemaRoot, Query, compileSchema } from 'decapi'

@SchemaRoot()
class SuperSchema {
  @Query()
  hello(name: string): string {
    return `Hello, ${name}!`
  }
}

const compiledSchema = compileSchema(SuperSchema)

compiledSchema is a regular GQL executable schema compatible with graphql-js library.

To use it with apollo-server, you'd have to use like this:

import ApolloServer from 'apollo-server'

const server = new ApolloServer({ schema, graphiql: true })

server.listen(3000, () =>
  console.log('Graphql API ready on http://localhost:3000/graphql')
)

Although it is encouraged to prefer fastify as it is a bit faster when used with jit.

Adding nested types

For now, our query field returned scalar (string). Let's return something more complex. Schema will look like:

mutation {
  createProduct(name: "Chair", price: 99.99) {
    name
    price
    isExpensive
  }
}

Such query will have a bit more code and here it is:

import {
  SchemaRoot,
  Query,
  ObjectType,
  Field,
  Mutation,
  compileSchema
} from 'decapi'

@ObjectType({ description: 'Simple product object type' })
class Product {
  @Field()
  name: string

  @Field()
  price: number

  @Field()
  isExpensive() {
    return this.price > 50
  }
}

@SchemaRoot()
class SuperSchema {
  @Mutation()
  createProduct(name: string, price: number): Product {
    const product = new Product()
    product.name = name
    product.price = price
    return product
  }
}

const compiledSchema = compileSchema(SuperSchema)

Type inference from typescript

These cases are supported by decapi 2/typescript-rtti:

  • Unions - for example we want to specify whether field is nullable or not
  • Function returns type of Promise<SomeType>
  • List (Array) type is used

All other code-first libraries on decorators like typegraphql or typegql require you to write types for these twice. Decapi infers types from typescript without any extra effort on your end.

Even in decapi 2 onward you still can write an explicit type. There are situations when typescript types are not precise enough- for example you want to be explicit about if some number type is Float or Int (GraphQLFloat or GraphQLInt).

Let's modify our Product so it has additional categories field that will return array of strings. For the sake of readability, let's ommit all fields we've defined previously.

@ObjectType()
class Product {
  @Field({ type: [String] }) // note we can use any native type like GraphQLString!
  categories(): string[] {
    return ['Tables', 'Furniture']
  }
}

We've added { type: [String] } as @Field options. Type can be anything that is resolvable to GraphQL type

  • Native JS scalars: String, Number, Boolean, Date.
  • Any type that is already compiled to graphql eg. GraphQLFloat or any type from external graphql library etc
  • Any class decorated with @ObjectType
  • an enum registered with registerEnum
  • Single element array for list types eg. [String] or [GraphQLFloat] or [MyEnum]

Writing Asynchronously

Every field function we write can be async and return Promise. Let's say, instead of hard-coding our categories, we want to fetch it from some external API:

@ObjectType()
class Product {
  @Field({ type: [String] }) // note we can use any native type like GraphQLString!
  async categories(): Promise<string[]> {
    const categories = await api.fetchCategories()
    return categories.map((cat) => cat.name)
  }
}

Upgrading from 1.0.0 to 2.0.0

Firstly, you must install all the new peer dependencies. This major was a complete rewrite of the reflection of types. From 2.0.0 decapi uses typescript-rtti to infer graphql types from typescript. This should work for all TS types. If you encounter a type which cannot be inferred, please raise an issue. This means you should always have your decorators without explicit type property.

Comparisons to other libraries

decapi does reflection through typescript-rtti, so it can always infer a type directly from typescript without having to write them twice. This is what sets it apart, but there are other differences:

type-graphql

There is a much more popular library with the same goals. Differences:

  1. decapi does reflection through typescript-rtti, so it can always infer a type directly from typescript without having to write them twice
  2. Decapi has smaller API surface-it only has hooks on top of the basic decorators for constructing schemas. Whereas type-graphql has authorization, middleware, guards.
  3. Also decapi supports graphql v16. Typegraphql is still only supporting Graphql v15

typegql

  • decapi has @DuplexObjectType and @DuplexField
  • decapi supports interfaces and mixins
  • decapi can infer Date type
  • decapi casts plain objects by default, which means it is much easier to use without ORMs. Even prisma needs this casting, because all the objects returned are POJO objects.
  • InputObjectType argument passed to Field/Query method is not just a plain object, but an instance of it's class.
  • decapi allows you to have an empty object type-you can populate it with fields at runtime

TC39 decorators proposal

Please if you enjoy decapi, go and star repo with the proposal-decorators . That's a way to show the TC39 members that you are using decorators and you want to have them in the language.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].