GraphQL server with Deno
Asked Answered
E

5

8

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');
Esplanade answered 21/5, 2020 at 20:8 Comment(0)
H
5
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})
Herzegovina answered 23/5, 2020 at 2:31 Comment(0)
C
5

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!

Corduroy answered 26/5, 2020 at 9:58 Comment(0)
M
0

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 });
Macgregor answered 21/5, 2020 at 20:16 Comment(1)
@HemantMetallia I rewrote my answer see if that solves your problemMacgregor
C
0

here is a code example using oak and middleware. You also can enjoy the playground GUI like an apollo one.

import { Application } from "https://deno.land/x/oak/mod.ts";
import { applyGraphQL, gql } from "https://deno.land/x/oak_graphql/mod.ts";

const app = new Application();

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.headers.get("X-Response-Time");
  console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`);
});

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.response.headers.set("X-Response-Time", `${ms}ms`);
});

const types = gql`
type User {
  firstName: String
  lastName: String
}

input UserInput {
  firstName: String
  lastName: String
}

type ResolveType {
  done: Boolean
}

type Query {
  getUser(id: String): User 
}

type Mutation {
  setUser(input: UserInput!): ResolveType!
}
`;

const resolvers = {
  Query: {
    getUser: (parent: any, {id}: any, context: any, info: any) => {
      console.log("id", id, context);
      return {
        firstName: "wooseok",
        lastName: "lee",
      };
    },
  },
  Mutation: {
    setUser: (parent: any, {firstName, lastName}: any, context: any, info: any) => {
      console.log("input:", firstName, lastName);
      return {
        done: true,
      };
    },
  },
};

const GraphQLService = applyGraphQL({
  typeDefs: types,
  resolvers: resolvers
})

app.use(GraphQLService.routes(), GraphQLService.allowedMethods());

console.log("Server start at http://localhost:8080");
await app.listen({ port: 8080 });
Corium answered 25/5, 2020 at 14:37 Comment(0)
Z
0

I have created gql for making GraphQL servers that aren't tied to a web framework. All of the responses above show Oak integration but you don't really have to use it to have a GraphQL server. You can go with std/http instead:

import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { GraphQLHTTP } from 'https://deno.land/x/gql/mod.ts'
import { makeExecutableSchema } from 'https://deno.land/x/graphql_tools/mod.ts'
import { gql } from 'https://deno.land/x/graphql_tag/mod.ts'

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

const resolvers = {
  Query: {
    hello: () => `Hello World!`
  }
}

const schema = makeExecutableSchema({ resolvers, typeDefs })

const s = serve({ port: 3000 })

for await (const req of s) {
  req.url.startsWith('/graphql')
    ? await GraphQLHTTP({
        schema,
        graphiql: true
      })(req)
    : req.respond({
        status: 404
      })
}
Zermatt answered 3/5, 2021 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.