Construir esquema con JavaScript
Anteriormente utilizamos el metodo buildSchema
para crear esquema para nuestra aplicacion integrada con GraphQL, a esta le pasabamos una plantilla literal (template literal) con la descripcion de nuestro esquema. Vamos ahora a crear el mismo esquema con JavaScript.
Antes vamos a definir los valores el cual estaremos utilizando en todo los ejemplos.
let video = {
id: '1',
title: 'Mattis ullamcorper velit sed ullamcorper',
duration: 180,
watched: false
}
let videos = [{
id: '1',
title: 'Mattis ullamcorper velit sed ullamcorper',
duration: 180,
watched: false
},{
id: '2',
title: 'Habitasse platea dictumst vestibulum',
duration: 240,
watched: true
},{
id: '3',
title: 'Urna et pharetra pharetra massa massa',
duration: 160,
watched: false
},{
id: '4',
title: 'Eu facilisis sed odio morbi',
duration: 260,
watched: true
},{
id: '5',
title: 'Egestas egestas fringilla phasellus',
duration: 190,
watched: false
},{
id: '6',
title: 'Pharetra massa massa ultricies',
duration: 160,
watched: false
}]
import express from 'express'
import graphqlHTTP from 'express-graphql'
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLInt,
GraphQLBoolean } from 'graphql'
const app = express()
const videoType = new GraphQLObjectType({
name: 'Video',
description: 'A video',
fields: {
id: {
type: GraphQLID,
description: 'Id of the video'
},
title: {
type: GraphQLString,
description: 'Title of the video'
},
duration: {
type: GraphQLInt,
description: 'Duration of the video'
},
watched: {
type: GraphQLBoolean,
description: 'Whether or not the viewer has watch the video'
}
}
})
const queryType = new GraphQLObjectType({
name: 'QueryType',
description: 'The root query type.',
fields: {
video: {
type: videoType,
resolve: () => new Promise((resolve) => {
resolve(video)
})
}
}
})
const schema = new GraphQLSchema({
query: queryType
})
// Graphql router
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // Set to false if you dont want graphiql enabled
}))
app.listen(3000, () => {
console.log(`Server listening on port ${PORT}`)
})
Query:
{
video {
id
title
duration
watched
}
}
Uso de argumentos para hacer busqueda por elemento especifico
import express from 'express'
import graphqlHTTP from 'express-graphql'
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLInt,
GraphQLBoolean } from 'graphql'
const app = express()
// Helper - In this case, it help to find element by ID
const getVideoById = (id) => new Promise((resolve) => {
const [video] = videos.filter((video) => {
return video.id === id
})
resolve(video)
})
const videoType = new GraphQLObjectType({
name: 'Video',
description: 'A video',
fields: {
id: {
type: GraphQLID,
description: 'Id of the video'
},
title: {
type: GraphQLString,
description: 'Title of the video'
},
duration: {
type: GraphQLInt,
description: 'Duration of the video'
},
watched: {
type: GraphQLBoolean,
description: 'Whether or not the viewer has watch the video'
}
}
})
const queryType = new GraphQLObjectType({
name: 'QueryType',
description: 'The root query type.',
fields: {
video: {
type: videoType,
// Include for used arguments
args: {
id: {
type: GraphQLID,
description: 'Id of the video'
}
},
// Including args we define step before
resolve: (_, args) => {
return getVideoById(args.id)
}
}
}
})
const schema = new GraphQLSchema({
query: queryType
})
// Graphql router
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // Set to false if you dont want graphiql enabled
}))
app.listen(3000, () => {
console.log(`Server listening on port ${PORT}`)
})
Query:
# Query 1
{
video(id: "1") {
title
duration
watched
}
}
# Query 2
{
video(id: "2") {
title
duration
watched
}
}
Evitar el retorno de valores nulos
En estos casos utilizamos el metodo GraphQLNonNull
para evitar tener retorno de valores nulos.
import express from 'express'
import graphqlHTTP from 'express-graphql'
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLInt,
GraphQLBoolean,
GraphQLNonNull } from 'graphql'
const app = express()
// Helper - In this case, it help to find element by ID
const getVideoById = (id) => new Promise((resolve) => {
const [video] = videos.filter((video) => {
return video.id === id
})
resolve(video)
})
const videoType = new GraphQLObjectType({
name: 'Video',
description: 'A video',
fields: {
id: {
type: GraphQLID,
description: 'Id of the video'
},
title: {
type: GraphQLString,
description: 'Title of the video'
},
duration: {
type: GraphQLInt,
description: 'Duration of the video'
},
watched: {
type: GraphQLBoolean,
description: 'Whether or not the viewer has watch the video'
}
}
})
const queryType = new GraphQLObjectType({
name: 'QueryType',
description: 'The root query type.',
fields: {
video: {
type: videoType,
args: {
id: {
// Used is required
type: new GraphQLNonNull(GraphQLID),
description: 'Id of the video'
}
},
resolve: (_, args) => {
return getVideoById(args.id)
}
}
}
})
const schema = new GraphQLSchema({
query: queryType
})
// Graphql router
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // Set to false if you dont want graphiql enabled
}))
app.listen(3000, () => {
console.log(`Server listening on port ${PORT}`)
})
Query:
# Query 1
{
video(id: "1") {
title
duration
watched
}
}
# Query 2
{
video(id: "2") {
title
duration
watched
}
}
Exponer todo los valores en lugar de un solo valor
En estos casos utilizamos el metodo GraphQLList
para devolver todos los elemento como lista.
import express from 'express'
import graphqlHTTP from 'express-graphql'
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLInt,
GraphQLBoolean,
GraphQLNonNull,
GraphQLList } from 'graphql'
const app = express()
// Helper - In this case, it help to find element by ID
const getVideoById = (id) => new Promise((resolve) => {
const [video] = videos.filter((video) => {
return video.id === id
})
resolve(video)
})
// Helper to get all video
const getVideos = () => new Promise((resolve) => resolve(videos))
const videoType = new GraphQLObjectType({
name: 'Video',
description: 'A video',
fields: {
id: {
type: GraphQLID,
description: 'Id of the video'
},
title: {
type: GraphQLString,
description: 'Title of the video'
},
duration: {
type: GraphQLInt,
description: 'Duration of the video'
},
watched: {
type: GraphQLBoolean,
description: 'Whether or not the viewer has watch the video'
}
}
})
const queryType = new GraphQLObjectType({
name: 'QueryType',
description: 'The root query type.',
fields: {
videos: {
type: new GraphQLList(videoType),
resolve: getVideos
},
video: {
type: videoType,
args: {
id: {
type: new GraphQLNonNull(GraphQLID),
description: 'Id of the video'
}
},
resolve: (_, args) => {
return getVideoById(args.id)
}
}
}
})
const schema = new GraphQLSchema({
query: queryType
})
// Graphql router
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // Set to false if you dont want graphiql enabled
}))
app.listen(3000, () => {
console.log(`Server listening on port ${PORT}`)
})
Query:
{
videos {
title
duration
watched
}
}