How to use apollo-server-micro - 10 common examples

To help you get started, we’ve selected a few apollo-server-micro examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github este / este / packages / api / index.ts View on Github external
},
  typegenAutoConfig: {
    // debug: true,
    sources: [{ source: path.join(__dirname, './types.ts'), alias: 'types' }],
    contextType: 'types.Context',
  },
  // backingTypeMap: {
  //   EmailAddress: 'string',
  //   DateTime: 'string',
  //   Max1024Chars: 'string',
  //   Max140Chars: 'string',
  //   URL: 'string',
  // },
});

const server = new ApolloServer({
  schema,
  context: async ({ req }: { req: IncomingMessage }): Promise => {
    if (req.headers.host == null) throw new Error('missing req.headers.host');
    const user = await getUser(API_SECRET, prisma, req);
    const models = createModels(prisma, user, req.headers.host);
    return { models };
  },
  // Enable introspection and playground for production.
  introspection: true,
  playground: true,
});

const { IS_NOW } = process.env;

const handler = withCORS(
  ports.api,
github charliewilco / downwrite / pages / api / graphql.ts View on Github external
import { ApolloServer } from "apollo-server-micro";
import { DownwriteAPI, schema } from "../../utils/graphql";
import { REST_ENDPOINT } from "../../utils/urls";

const server = new ApolloServer({
  schema,
  async context({ req }) {
    const token: string = req.cookies.DW_TOKEN || req.headers.authorization;
    return {
      authScope,
      token
    };
  },
  playground: {
    settings: {
      "editor.fontFamily": "Operator Mono, monospace"
      // "schema.polling.enable": false
    }
  },
  dataSources() {
    return {
github charliewilco / downwrite / pages / api / graphql.ts View on Github external
import { ApolloServer } from "apollo-server-micro";
import { importSchema } from "graphql-import";

import jwt from "jsonwebtoken";
import Mongoose from "mongoose";
import { NextApiRequest, NextApiResponse } from "next";
import { resolvers, IResolverContext } from "../../utils/resolvers";
import { IUser, IPost, PostModel, UserModel } from "../../utils/models";
import { MongoSource } from "../../utils/data-source";
import { prepareDB } from "../../utils/prepare-db";

const typeDefs = importSchema("pages/api/schema.graphql");

let connection: typeof Mongoose;

const server = new ApolloServer({
  typeDefs,
  resolvers,
  async context({ req }) {
    const token: string = req.cookies.DW_TOKEN || req.headers.authorization;
    const authScope = jwt.decode(token);
    connection = await prepareDB();
    return {
      authScope
    };
  },
  playground: {
    settings: {
      "editor.fontFamily": "Operator Mono, monospace",
      "editor.theme": "light"
      // "schema.polling.enable": false
    }
github este / este / packages / api / models / createPermissions.ts View on Github external
const isWebCreatorOrAdmin = (web: NexusGenAllTypes['Web']) => {
    const viewer = isAuthenticated();
    // TODO: if (viewer.isAdmin) return;
    if (viewer.id === web.creator.id) return;
    throw new ForbiddenError('you must be web creator or admin');
  };
github fanout / fanout-graphql-tools / examples / micro / src / index.ts View on Github external
IStoredPubSubSubscription,
  WebSocketOverHttpContextFunction,
} from "fanout-graphql-tools";
import { MapSimpleTable } from "fanout-graphql-tools";
import * as http from "http";
import micro from "micro";
import { SimpleGraphqlApi } from "../../../src/simple-graphql-api/SimpleGraphqlApi";

/**
 * WebSocket-Over-HTTP Support requires storage to keep track of ws-over-http connections and subscriptions.
 * The Storage objects match an ISimpleTable interface that is a subset of the @pulumi/cloud Table interface. MapSimpleTable is an in-memory implementation, but you can use @pulumi/cloud implementations in production, e.g. to use DyanmoDB.
 */
const connectionStorage = MapSimpleTable();
const pubSubSubscriptionStorage = MapSimpleTable();

const schema = makeExecutableSchema(SimpleGraphqlApi());

const apolloServer = new ApolloServer({
  context: WebSocketOverHttpContextFunction({
    grip: {
      // Get this from your Fanout Cloud console, which looks like https://api.fanout.io/realm/{realm-id}?iss={realm-id}&key=base64:{realm-key}
      // or use this localhost for your own pushpin.org default installation
      url: process.env.GRIP_URL || "http://localhost:5561",
    },
    pubSubSubscriptionStorage,
    schema,
  }),
  schema,
});

// Note: In micro 9.3.5 this will return an http.RequestListener instead (after https://github.com/zeit/micro/pull/399)
// Provide it to http.createServer to create an http.Server
github firstmeanseverything / api.firstmeanseverything.com / graphql / index.js View on Github external
const { ApolloServer } = require('apollo-server-micro')
const db = require('@firstmeanseverything/db')
const { makeExecutableSchema } = require('graphql-tools')
const { applyMiddleware } = require('graphql-middleware')

const resolvers = require('./resolvers')
const loaders = require('./loaders')
const permissions = require('./permissions')
const typeDefs = require('./typeDefs')
const { getUserId, withCors } = require('./utils')

const server = new ApolloServer({
  schema: applyMiddleware(
    makeExecutableSchema({
      typeDefs,
      resolvers,
      inheritResolversFromInterfaces: true
    }),
    permissions
  ),
  context: async req => ({
    ...req,
    db,
    loaders,
    userId: await getUserId({ ...req })
  }),
  introspection: true,
  playground: true
github sync / reason-graphql-demo / src / pages / api / graphql.ts View on Github external
const resolvers = {
  Query: {
    subreddit: async (_: any, { name }) => {
      const response: SubredditData = await fetch(
        `https://www.reddit.com/r/${name}.json`,
      ).then(r => r.json());
      return response && response.data;
    },
  },
  Subreddit: {
    posts: (subreddit: Subreddit) =>
      subreddit ? subreddit.children.map(child => child.data) : [],
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true,
  playground: true,
});

export const config = {
  api: {
    bodyParser: false,
  },
};

export default server.createHandler({ path: '/api/graphql' });
github ealmansi / graphqlzero / gqlz-web / api / server.js View on Github external
photo_1.typeDefs,
        post_1.typeDefs,
        todo_1.typeDefs,
        user_1.typeDefs,
    ];
    var resolvers = {
        Query: __assign({}, album_1.resolvers.Query, comment_1.resolvers.Query, page_1.resolvers.Query, photo_1.resolvers.Query, post_1.resolvers.Query, todo_1.resolvers.Query, user_1.resolvers.Query),
        Mutation: __assign({}, album_1.resolvers.Mutation, comment_1.resolvers.Mutation, page_1.resolvers.Mutation, photo_1.resolvers.Mutation, post_1.resolvers.Mutation, todo_1.resolvers.Mutation, user_1.resolvers.Mutation),
        Album: album_1.resolvers.Album,
        Comment: comment_1.resolvers.Comment,
        Photo: photo_1.resolvers.Photo,
        Post: post_1.resolvers.Post,
        Todo: todo_1.resolvers.Todo,
        User: user_1.resolvers.User,
    };
    return new apollo_server_micro_1.ApolloServer({
        typeDefs: typeDefs,
        resolvers: resolvers,
        introspection: true,
        playground: {
            settings: {
                'editor.theme': 'light',
            }
        }
    });
}
exports.buildApolloServer = buildApolloServer;
github kitten / graphql-box / scripts / demo.js View on Github external
id: ID! @unique
  hash: String! @unique
  message: String
  files: [File]!
}

type File {
  id: ID! @unique
  createdAt: DateTime!
  name: String!
}
`;

const schema = makeExecutableSchema(sdl, memdown());

const apolloServer = new ApolloServer({ schema, tracing: true });
module.exports = apolloServer.createHandler();