How to use the apollo-server-koa.ApolloServer function in apollo-server-koa

To help you get started, we’ve selected a few apollo-server-koa 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 sharynjs / sharyn / packages / koa / src / index.js View on Github external
app.use(
      // flow-disable-next-line
      require('koa-favicon')(
        `./${pathCascade(
          'public/img/favicon/favicon.ico',
          'public/img/favicon.ico',
          'public/favicon.ico',
        )}`,
      ),
    )
  }

  if (hasPackage('apollo-server-koa')) {
    // flow-disable-next-line
    const { ApolloServer } = require('apollo-server-koa')
    const apolloServer = new ApolloServer(options?.apolloConfig ?? {})
    apolloServer.applyMiddleware({ app })
  }

  routing(router)
  app.use(router.routes()).use(router.allowedMethods())

  app.on('error', err => console.error(err))

  server = app.listen(options?.port || port)
}
github oneqljs / oneQL / src / index.ts View on Github external
init() {
    let { schema, ...other } = this.props

    const server = new ApolloServer({
      schema: makeExecutableSchema(schema),
      ...other
      // // playground: false
      // context: async ({ ctx }: Koa.Context) => {
      //   const { cookie, request } = ctx
      //   const { body }: { body: { head } } = request || {}
      //   const { head = {} } = body || {}
      //   const { cticket, auth }: {
      //     cticket?: String
      //     auth?: String
      //   } = cookie || {}
      //   return {
      //     token: cticket || auth || '',
      //     head,
      //     db: 'dbdbb',
      //     ctx
github naihe138 / GraphQL-demo / src / app.js View on Github external
const Koa = require('koa')
const KoaStatic = require('koa-static')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const { ApolloServer } = require('apollo-server-koa')
require('./mongodb')
const routerMap = require('./router')
const { typeDefs, resolvers } = require('./graphql/schema')
const app = new Koa()
const router = new Router()
const apollo = new ApolloServer({ typeDefs, resolvers })

app.use(bodyParser())
app.use(KoaStatic(__dirname + '/static'))
// 路由配置
router.use(routerMap.routes())
// 使用路由
app.use(router.routes())
app.use(router.allowedMethods())
// 使用apollo
app.use(apollo.getMiddleware())

app.listen(4000, () => {
   console.log('🚀 GraphQL-demo server listen at http://localhost:4000\n')
   console.log(`🚀 Server ready at http://localhost:4000${apollo.graphqlPath}`)
})
github jaydenseric / apollo-upload-examples / api / server.js View on Github external
stream.on('error', error => writeStream.destroy(error))

    // Pipe the upload into the write stream.
    stream.pipe(writeStream)
  })

  // Record the file metadata in the DB.
  db.get('uploads')
    .push(file)
    .write()

  return file
}

const app = new Koa()
const server = new ApolloServer({
  uploads: {
    // Limits here should be stricter than config for surrounding
    // infrastructure such as Nginx so errors can be handled elegantly by
    // graphql-upload:
    // https://github.com/jaydenseric/graphql-upload#type-processrequestoptions
    maxFileSize: 10000000, // 10 MB
    maxFiles: 20
  },
  schema,
  context: { db, storeUpload }
})

server.applyMiddleware({ app })

app.listen(process.env.PORT, error => {
  if (error) throw error
github strvcom / nodejs-open-knowledge / src / graphql / index.js View on Github external
function addGraphQL(app) {
  const enableIntrospection = config.env !== 'production'
  const engineConfig = config.apolloEngineApiKey
    ? { apiKey: config.apolloEngineApiKey }
    : false

  // Create Apollo server
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    debug: enableIntrospection,
    introspection: enableIntrospection,
    playground: enableIntrospection ? defaultPlaygroundConfig : false,
    context: makeContext,
    formatError,
    engine: engineConfig,
  })

  // Apply Apollo middleware
  server.applyMiddleware({
    app,
    path: '/graphql',
  })
}
github caiyongmin / graphql-basedon-restful / src / index.ts View on Github external
const schema: GraphQLSchema = makeExecutableSchema({
    typeDefs,
    schemaDirectives: {
      rest: RestDirective
    },
  });

  if (mocks) {
    addMockFunctionsToSchema({
      schema,
      mocks: typeof mocks === 'boolean' ? {} : mocks,
      preserveResolvers: true,
    });
  }

  return new ApolloServer({
    schema,
    context: () => ({
      endpointMap,
      // TODO: permission verification will be added
      restLoader: createRestLoader(),
    }),
    resolvers: {
      Date: dateScalarType,
    },
  });
};
github cofacts / rumors-api / src / index.js View on Github external
ctx.body = { success: true };
});

router.options('/graphql', checkHeaders());
router.post('/graphql', checkHeaders());

const indexFn = pug.compileFile(path.join(__dirname, 'jade/index.jade'));
const schemaStr = printSchema(schema);
router.get('/', ctx => {
  ctx.body = indexFn({ schemaStr });
});

app.use(koaStatic(path.join(__dirname, '../static/')));
app.use(router.routes(), router.allowedMethods());

const apolloServer = new ApolloServer({
  schema,
  introspection: true, // Allow introspection in production as well
  playground: true,
  context: ({ ctx }) => ({
    loaders: new DataLoaders(), // new loaders per request
    user: ctx.state.user,

    // userId-appId pair
    //
    userId:
      ctx.appId === 'WEBSITE' || ctx.appId === 'DEVELOPMENT_FRONTEND'
        ? (ctx.state.user || {}).id
        : ctx.query.userId,
    appId: ctx.appId,
  }),
  formatError(err) {
github naihe138 / GraphQL-demo / start.js View on Github external
const { ApolloServer, gql } = require('apollo-server-koa')


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

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

const server = new ApolloServer({ typeDefs, resolvers })

const app = new Koa()
app.use(server.getMiddleware())

app.listen({ port: 4000 }, () =>
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
)
github fullstack-build / fullstack-one / packages / graphql / lib / koaMiddleware.ts View on Github external
function createApolloServer(schema: GraphQLSchema, { graphiQlEndpointActive }: IGraphQlConfig, logger: ILogger): ApolloServer {
  const koaGraphQlConfig = getKoaGraphQLOptionsFunction(schema, logger);

  koaGraphQlConfig.playground = graphiQlEndpointActive === true;

  const server = new ApolloServer(koaGraphQlConfig);

  return server;
}
github shfshanyue / apollo-server-starter / index.ts View on Github external
import { formatError, Exception, responseLogger, queryLogger, session, redis } from './lib'
import { typeDefs, resolvers } from './src'
import directives from './src/directives'
import * as utils from './src/utils'
import sequelize, { models, contextOption } from './db'
import config from './config'
import { AppContext, KoaContext } from './type'
import { auth, context } from './middlewares'
import httpStatusPlugin from './src/plugin/httpStatus'

const cache = new RedisCache({
  host: config.redis.host,
  password: config.redis.password
})

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context ({ ctx }: { ctx: KoaContext }): AppContext {
    const body = ctx.request.body || {}
    queryLogger.info(body.query, {
      operationName: body.operationName,
      query: body.query,
      variables: body.variables,
      ip: ctx.request.ip,
      user: ctx.user
    })
    return {
      sequelize,
      contextOption,
      models,
      config,