Demo: https://codesandbox.io/s/5yknn3jjzp
If you have ideas or want to contribute feel free to open issues or pull requests 😊
yarn add @n1ru4l/apollo-link-rest
Generate an executable Schema from typeDefs annotated with @rest
directives
This can be used by apollo-server or a schema link.
type User {
id: ID!
login: String!
friends: [User]!
@rest(
route: "/users/:userId/friends"
provides: { userId: "id" } # map id from parent object to :userId route param
)
}
type Query {
user(id: ID!): User @rest(route: "/users/:id")
}
import { generateRestSchema } from 'apollo-rest-link'
import { graphql } from 'graphql'
import fetch from 'node-fetch'
const typeDefs = `
type User {
id: ID!
login: String!
friends: [User]!
@rest(
route: "/users/:userId/friends"
provides: { userId: "id" } # map id from parent object to :userId route param
)
}
type Query {
user(id: ID!): User @rest(route: "/users/:id")
}
`
const schema = generateRestSchema({
typeDefs,
fetcher: fetch,
})
const query = `
query user {
user(id: "2") {
id
login
friends {
id
login
}
}
}
`
graphql(schema, query)
.then(console.log)
.catch(console.log)
Query a generated schema.
import { generateRestSchema, createSchemaLink } from 'apollo-rest-link'
import { execute, makePromise } from 'apollo-link'
import gql from 'graphql-tag'
import fetch from 'node-fetch'
const typeDefs = `
type User {
id: ID!
login: String!
friends: [User]!
@rest(
route: "/users/:userId/friends"
provides: { userId: "id" } # map id from parent object to :userId route param
)
}
type Query {
user(id: ID!): User @rest(route: "/users/:id")
}
`
const schema = generateRestSchema({
typeDefs,
fetcher: fetch,
})
const link = createSchemaLink({ schema })
const query = gql`
query user {
user(id: "2") {
id
login
friends {
id
login
}
}
}
`
makePromise(execute(link, { operationName: `userProfile`, query }))
.then(console.log)
.catch(console.log)
This implementation uses query directives and maps them to rest endpoints. At the moment there is only support for queries which are mapped to GET requests
query userProfile($id: ID!) {
userProfile(id: $id) @rest(type: "User", route: "/users/:id", params: { id: $id }) {
id
login
friends @rest(
type: "User"
route: "/users/:userId/friends"
provides: { userId: "id" } # map id from parent object to :userId route param
) {
id
login
}
}
}
import gql from 'graphql-tag'
import { execute, makePromise } from 'apollo-link'
import fetch from 'node-fetch'
import { createRestLink } from 'apollo-rest-link'
const link = createRestLink({ fetcher: fetch })
const query = gql`
query userProfile($id: ID!) {
userProfile(id: $id) @rest(type: "User", route: "/users/:id", params: { id: $id }) {
id
login
friends @rest(
type: "User"
route: "/users/:userId/friends"
provides: { userId: "id" } # map id from parent object to :userId route param
) {
id
login
}
}
}
`
makePromise(execute(link, { operationName: `userProfile`, query }))
.then(console.log)
.catch(console.log)
yarn test