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

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 velopert / velog-server / src / graphql / series.ts View on Github external
}

      // reorder series
      // validate series order
      const seriesPostsRepo = getRepository(SeriesPosts);
      const seriesPosts = await seriesPostsRepo.find({
        where: {
          fk_series_id: id
        }
      });

      const valid =
        seriesPosts.every(sp => series_order.includes(sp.id)) &&
        seriesPosts.length === series_order.length;
      if (!valid) {
        throw new ApolloError('series_order is invalid', 'BAD_REQUEST');
      }

      // figure out which data to update
      const seriesPostsById = normalize(seriesPosts, sp => sp.id);
      type Update = { id: string; index: number };
      const updates = series_order.reduce((acc, current, index) => {
        const sp = seriesPostsById[current];
        console.log(sp.index, index + 1);
        if (sp.index !== index + 1) {
          // index mismatch
          acc.push({
            id: current,
            index: index + 1
          });
          return acc;
        }
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 velopert / velog-server / src / graphql / series.ts View on Github external
const { series_id, post_id } = args as AppendToSeriesArgs;
      await getSeriesIfValid(series_id, ctx.user_id);

      const seriesPostsRepo = getRepository(SeriesPosts);
      const seriesPostsList = await seriesPostsRepo.find({
        where: {
          fk_series_id: series_id
        },
        order: {
          index: 'ASC'
        }
      });
      const exists = seriesPostsList.find(sp => sp.fk_post_id === post_id);

      if (exists) {
        throw new ApolloError('Already added to series', 'CONFLICT');
      }

      const nextIndex =
        seriesPostsList.length === 0 ? 1 : seriesPostsList[seriesPostsList.length - 1].index + 1;

      // create new seriesPost
      const seriesPosts = new SeriesPosts();
      seriesPosts.fk_post_id = post_id;
      seriesPosts.fk_series_id = series_id;
      seriesPosts.index = nextIndex;

      // save
      await seriesPostsRepo.save(seriesPosts);
      return nextIndex;
    },
    editSeries: async (parent, args, ctx) => {
github velopert / velog-server / src / graphql / post.ts View on Github external
createPostHistory: async (parent: any, args: CreatePostHistoryArgs, ctx) => {
      if (!ctx.user_id) {
        throw new AuthenticationError('Not Logged In');
      }

      // check ownPost
      const { post_id, title, body, is_markdown } = args;

      const postRepo = getRepository(Post);
      const post = await postRepo.findOne(post_id);

      if (!post) {
        throw new ApolloError('Post not found', 'NOT_FOUND');
      }
      if (post.fk_user_id !== ctx.user_id) {
        throw new ApolloError('This post is not yours', 'NO_PERMISSION');
      }

      // create postHistory
      const postHistoryRepo = getRepository(PostHistory);
      const postHistory = new PostHistory();
      Object.assign(postHistory, { title, body, is_markdown, fk_post_id: post_id });

      await postHistoryRepo.save(postHistory);

      const [data, count] = await postHistoryRepo.findAndCount({
        where: {
          fk_post_id: post_id
        },