Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const fs = require("fs");
const path = require("path");
const express = require("express");
const { postgraphile } = require("postgraphile");
const PostGraphileUploadFieldPlugin = require("postgraphile-plugin-upload-field");
const { graphqlUploadExpress } = require("graphql-upload");
const app = express();
const UPLOAD_DIR_NAME = "uploads";
// Serve uploads as static resources
app.use(`/${UPLOAD_DIR_NAME}`, express.static(path.resolve(UPLOAD_DIR_NAME)));
// Attach multipart request handling middleware
app.use(graphqlUploadExpress());
app.use(
postgraphile("postgres://localhost:5432/upload_example", "public", {
graphiql: true,
enableCors: true,
appendPlugins: [PostGraphileUploadFieldPlugin],
graphileBuildOptions: {
uploadFieldDefinitions: [
{
match: ({ column }) => column === "header_image_file",
resolve: resolveUpload,
},
],
},
})
);
session({
secret: process.env.SESSION_KEY,
resave: false,
saveUninitialized: true,
cookie: { httpOnly: true, maxAge: 86400000 },
}),
);
initPassport(app);
app.use(logger('dev'));
app.use('/account', require('./api/routes/account-route'));
app.use(
'/graphql',
// isAuthenticated,
graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
graphqlHTTP({
schema,
graphiql: process.env.NODE_ENV === 'development',
}),
);
app.use((req, res, next) => {
next(createError(404));
});
app.use((err, req, res, next) => {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// 나중에 에러 처리는 상세히
res.status(err.status || 500).json({});
) => DocumentNode = gqlTag;
import runtimeSupportsUploads from './utils/runtimeSupportsUploads';
import { GraphQLScalarType } from 'graphql';
export { default as processFileUploads } from './processFileUploads';
// This is a conditional export intended to avoid traversing the
// entire module tree of `graphql-upload`. This only defined if the
// version of Node.js is >= 8.5.0 since those are the only Node.js versions
// which are supported by `graphql-upload@8`. Since the source of
// `graphql-upload` is not transpiled for older targets (in fact, it includes
// experimental ECMAScript modules), this conditional export is necessary
// to avoid modern ECMAScript from failing to parse by versions of Node.js
// which don't support it (yet — eg. Node.js 6 and async/await).
export const GraphQLUpload = runtimeSupportsUploads
? (require('graphql-upload').GraphQLUpload as GraphQLScalarType)
: undefined;
"use strict";
/*
GraphQL Plugin default options for base schema and resolvers
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const apollo_server_caching_1 = require("apollo-server-caching");
const graphql_upload_1 = require("graphql-upload");
const graphql_type_json_1 = require("graphql-type-json");
const graphql_iso_date_1 = require("graphql-iso-date");
// TODO: as preset
delete graphql_upload_1.GraphQLUpload.description;
delete graphql_type_json_1.GraphQLJSON.description;
delete graphql_iso_date_1.GraphQLDate.description;
delete graphql_iso_date_1.GraphQLDateTime.description;
delete graphql_iso_date_1.GraphQLTime.description;
const typeDefs = [];
const resolvers = {};
/* default scalar types */
typeDefs.push(`
"""
Upload scalar type
@input: [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec)
@output: { filename, mimetype, encoding, createReadStream }
filename string File name.
mimetype string File MIME type. Provided by the client and can’t be trusted.
encoding string File stream transfer encoding.
createReadStream Function Returns a Node.js readable stream of the file contents, for processing and storing the file. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request.
const typeDefs = [];
const resolvers = {};
/* default scalar types */
typeDefs.push(`
"""
Upload scalar type
@input: [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec)
@output: { filename, mimetype, encoding, createReadStream }
filename string File name.
mimetype string File MIME type. Provided by the client and can’t be trusted.
encoding string File stream transfer encoding.
createReadStream Function Returns a Node.js readable stream of the file contents, for processing and storing the file. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request.
"""
scalar Upload
`);
resolvers.Upload = graphql_upload_1.GraphQLUpload;
typeDefs.push(`
"""
JSON scalar type
@input: JSON string
@output: Result of JSON.parse(@input)
"""
scalar JSON
`);
resolvers.JSON = graphql_type_json_1.GraphQLJSON;
typeDefs.push(`
"""
Date scalar type
@input: RFC3339 full-date string: "2007-12-03"
@output: Date instance
"""
scalar Date
import { graphqlUploadKoa } from 'graphql-upload'
import { GraphQLServiceContext } from '../typings'
const graphqlUpload = graphqlUploadKoa({
maxFieldSize: 1e6, // size in Bytes
maxFileSize: 4 * 1e6, // size in Bytes
maxFiles: 10,
})
function graphqlUploadKoaMiddleware(
ctx: GraphQLServiceContext,
next: () => Promise
): Promise {
return graphqlUpload(ctx as any, next)
}
export const upload = graphqlUploadKoaMiddleware
import { graphqlUploadKoa } from 'graphql-upload'
import { GraphQLServiceContext } from '../typings'
declare module 'graphql-upload' {
export function graphqlUploadKoa(options: ApolloUploadOptions): (ctx: GraphQLServiceContext, next: () => Promise) => Promise
}
export const upload = graphqlUploadKoa({
maxFieldSize: 1e6, // size in Bytes
maxFileSize: 4 * 1e6, // size in Bytes
maxFiles: 5,
})
/*
GraphQL Plugin default options for base schema and resolvers
*/
import { GraphQLHandlersOptions } from "./handlers";
import { InMemoryLRUCache } from "apollo-server-caching";
import { GraphQLUpload } from "graphql-upload";
import { GraphQLJSON } from "graphql-type-json";
import { GraphQLDate, GraphQLDateTime, GraphQLTime } from "graphql-iso-date";
// TODO: as preset
delete GraphQLUpload.description;
delete GraphQLJSON.description;
delete GraphQLDate.description;
delete GraphQLDateTime.description;
delete GraphQLTime.description;
const typeDefs: string[] = [];
const resolvers: any = {};
/* default scalar types */
typeDefs.push(`
"""
Upload scalar type
@input: [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec)
@output: { filename, mimetype, encoding, createReadStream }
filename string File name.
mimetype string File MIME type. Provided by the client and can’t be trusted.
return async (req, res) => {
this.graphqlPath = path || "/graphql";
await promiseWillStart;
// If file uploads are detected, prepare them for easier handling with
// the help of `graphql-upload`.
if (this.uploadsConfig) {
const contentType = req.headers["content-type"];
if (contentType && contentType.startsWith("multipart/form-data")) {
req.filePayload = await processRequest(req, res, this.uploadsConfig);
}
}
// If health checking is enabled, trigger the `onHealthCheck`
// function when the health check URL is requested.
if (!disableHealthCheck && req.url === "/.well-known/apollo/server-health")
return await this.handleHealthCheck({ req, res, onHealthCheck });
// If the `playgroundOptions` are set, register a `graphql-playground` instance
// (not available in production) that is then used to handle all
// incoming GraphQL requests.
if (this.playgroundOptions && req.method === "GET") {
const { mediaTypes } = accept.parseAll(req.headers);
const prefersHTML =
mediaTypes.find(x => x === "text/html" || x === "application/json") ===
"text/html";
applyGraphQL(app) {
if (!app || !app.use) {
requiredParameter('You must provide an Express.js app instance!');
}
app.use(
this.config.graphQLPath,
graphqlUploadExpress({
maxFileSize: this._transformMaxUploadSizeToBytes(
this.parseServer.config.maxUploadSize || '20mb'
),
})
);
app.use(this.config.graphQLPath, corsMiddleware());
app.use(this.config.graphQLPath, bodyParser.json());
app.use(this.config.graphQLPath, handleParseHeaders);
app.use(this.config.graphQLPath, handleParseErrors);
app.use(
this.config.graphQLPath,
graphqlExpress(async req => await this._getGraphQLOptions(req))
);
}