Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL server with Deno

It works just once for the below code

import {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import { serve } from "https://deno.land/[email protected]/http/server.ts";

var schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: "RootQueryType",
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return "world";
        },
      },
    },
  }),
});

var query = "{ hello }";

graphql(schema, query).then((result) => {
  console.log(result);
});

How to keep it listening, just like express Something like this

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
like image 380
Hemant Metallia Avatar asked May 21 '20 20:05

Hemant Metallia


3 Answers

import {
    graphql,
    buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import {Application, Router} from "https://deno.land/x/oak/mod.ts";

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var resolver = {hello: () => 'Hello world!'}

const executeSchema = async (query:any) => {
    const result = await graphql(schema, query, resolver);   
    return result;
}

var router = new Router();

router.post("/graph", async ({request, response}) => {
    if(request.hasBody) {
        const body = await request.body();
        const result = await executeSchema(body.value);
        response.body = result;
    } else {
        response.body = "Query Unknown";
    }
})


let app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server running");
app.listen({port: 5000})
like image 154
Rakesh Jain Avatar answered Nov 07 '22 15:11

Rakesh Jain


You can now use https://deno.land/x/deno_graphql to achieve this goal.

It provides everything needed out-of-the-box and works with multiple Deno frameworks (oak, abc, attain, etc).

This is how you code looks like (with oak for example):

import { Application, Context, Router } from "https://deno.land/x/oak/mod.ts";
import {
  gql,
  graphqlHttp,
  makeExecutableSchema,
} from "https://deno.land/x/deno_graphql/oak.ts";

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => "Hello world!",
  },
};

const context = (context: Context) => ({
  request: context.request,
});

const schema = makeExecutableSchema({ typeDefs, resolvers });

const app = new Application();
const router = new Router();

router.post("/graphql", graphqlHttp({ schema, context }));

app.use(router.routes());

await app.listen({ port: 4000 });

PS : i'm the author of the package, so you can ask me anything.

Hope this helps!

like image 5
cvng Avatar answered Nov 07 '22 17:11

cvng


Here is an example using oak working with your GraphQL code.

First let's say you have a repository graphRepository.ts with your graph schema:

import {
    graphql,
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLString
} from "https://cdn.pika.dev/graphql/^15.0.0";

var schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: "RootQueryType",
        fields: {
            hello: {
                type: GraphQLString,
                resolve() {
                    return "world";
                },
            },
        },
    }),
});

export async function querySchema(query: any) {
    return await graphql(schema, query)
        .then(async (result) => {
            return result;
        });
}

Now start your app.ts listener with the routes, and use the following URL to call the endpoint:

http://localhost:8000/graph/query/hello

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { querySchema } from "./graphRepository.ts";

const router = new Router();

router
    .get("/graph/query/:value", async (context) => {
        const queryValue: any = context.params.value;
        const query = `{ ${queryValue}}`
        const result = await querySchema(query);
        console.log(result)
        context.response.body = result;
    })

const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({ port: 8000 });
like image 1
Evandro Pomatti Avatar answered Nov 07 '22 15:11

Evandro Pomatti