Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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)
}
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
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}`)
})
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
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',
})
}
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,
},
});
};
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) {
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}`)
)
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;
}
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,