web-dev-qa-db-ja.com

Denoを備えたGraphQLサーバー

以下のコードで一度だけ機能します

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);
});

expressのようにリッスンし続ける方法

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');
7
Hemant Metallia

プレイグラウンドGUIで「エラー」:「JSON入力の予期しない終了」、これを解決するための提案

0
devesh shendkar

次に、GraphQLコードで Oak を使用する例を示します。

最初に、リポジトリがあるとしましょうgraphRepository.tsグラフスキーマ:

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;
        });
}

app.tsリスナーとルート、次のURLを使用してエンドポイントを呼び出します。

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 });
0
Evandro Pomatti

以下は、Oakとミドルウェアを使用したコード例です。アポロのような遊び場GUIを楽しむこともできます。

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 });
0
Aaron Lee