Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import express from 'express'
import postgraphile from 'postgraphile'
// import PluginName from './plugins/PluginName'
// const plugins = [
// PluginName
// ]
const app = express()
const pgConnectionString = process.env.DB_URI
const pgSchemas = process.env.POSTGRAPHILE_SCHEMAS.split(',')
const pgOptions = JSON.parse(process.env.POSTGRAPHILE_OPTIONS)
// pgOptions.appendPlugins = plugins
app.use(postgraphile(pgConnectionString, pgSchemas, pgOptions))
app.listen(3000, '0.0.0.0', function () {
console.info('NODE_ENV: ' + process.env.NODE_ENV)
console.info('Postgraphile API started.\n')
})
const PgSimplifyInflectorPlugin = require('@graphile-contrib/pg-simplify-inflector');
const PgIdToRowIdInflectorPlugin = require('./plugins/PgIdToRowIdInflectorPlugin');
const PgNonNullRelationsPlugin = require('@graphile-contrib/pg-non-null/relations');
// constants
const postgresUser = process.env.POSTGRES_USER;
const postgresPassword = process.env.POSTGRES_PASSWORD;
const postgresPort = process.env.POSTGRES_PORT;
const postgresDb = process.env.POSTGRES_DB;
const noAuth = !!process.env.NO_AUTH;
console.log(`Starting PostGraphile${noAuth ? ' in no-auth mode' : ''}...\n`);
http
.createServer(
postgraphile(
`postgres://${postgresUser}:${postgresPassword}@postgres:${postgresPort}/${postgresDb}`,
'public', // introspected schema
{
classicIds: true,
dynamicJson: true,
setofFunctionsContainNulls: false,
ignoreRBAC: false,
pgDefaultRole: noAuth ? 'viewer' : 'anonymous',
disableDefaultMutations: true,
disableQueryLog: false,
jwtSecret: process.env.POSTGRAPHILE_JWT_SECRET,
graphiql: true,
watchPg: true,
jwtPgTypeIdentifier: 'private.jwt_token',
graphileBuildOptions: {
pgStrictFunctions: true,
} else {
console.log();
console.log(
`Please support PostGraphile development:\n\n ${chalk.blue.bold.underline(
"https://graphile.org/donate"
)} 🙏`
);
console.log();
}
/* eslint-enable */
const isDev = process.env.NODE_ENV === "development";
const isTest = process.env.NODE_ENV === "test";
/* Load any PostGraphile server plugins (different from Graphile Engine schema plugins) */
const pluginHook = makePluginHook([PgPubsub, PostGraphilePro].filter(_ => _));
/*
* This function generates the options for a PostGraphile instance to use. We
* make it a separate function call so that we may call it from other places
* (such as tests) and even parameterise it if we want.
*/
function postgraphileOptions(overrides) {
return {
// This is for PostGraphile server plugins: https://www.graphile.org/postgraphile/plugins/
pluginHook,
// This is so that PostGraphile installs the watch fixtures, it's also needed to enable live queries
ownerConnectionString: process.env.DATABASE_URL,
// Add websocket support to the PostGraphile server; you still need to use a subscriptions plugin such as
// @graphile/pg-pubsub
const express = require('express')
const { postgraphile } = require('postgraphile')
const { Pool } = require('pg')
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
})
const app = express()
const postgraphileInstance = postgraphile(pool, process.env.DB_SCHEMA, {
// Dev, debug, test
graphiql: process.env.NODE_ENV === 'development',
enhanceGraphiql: process.env.NODE_ENV === 'development',
// JWT Authentication
jwtSecret: process.env.JWT_SECRET,
defaultRole: process.env.JWT_ROLE,
jwtPgTypeIdentifier: process.env.JWT_TOKEN,
// Postgraphile recommended config
setofFunctionsContainNulls: true,
// If none of your RETURNS SETOF compound_type functions
// mix NULLs with the results
// then you may set this true
// to reduce the nullables in the GraphQL schema.
ignoreRBAC: false,
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,
},
],
},
})
);
app.listen(5000, () => {
// eslint-disable-next-line
module.exports = app => {
const httpServer = app.get("httpServer");
const authPgPool = app.get("authPgPool");
/*
* If we're using subscriptions, they may want access to sessions/etc. Make
* sure any websocketMiddlewares are installed before this point. Note that
* socket middlewares must always call `next()`, otherwise you're going to
* have some issues.
*/
const websocketMiddlewares = app.get("websocketMiddlewares");
// Install the PostGraphile middleware
const middleware = postgraphile(
authPgPool,
"app_public",
postgraphileOptions({
websocketMiddlewares,
})
);
app.use(middleware);
if (enhanceHttpServerWithSubscriptions) {
enhanceHttpServerWithSubscriptions(httpServer, middleware);
}
};
if (!this.httpAdapterHost) {
return;
}
const httpAdapter = this.httpAdapterHost.httpAdapter;
if (!httpAdapter) {
return;
}
const app = httpAdapter.getInstance();
// Break out PostGraphile options
const {pgConfig, schema, playground, ...postGraphileOptions} = this.options;
if (schema) {
this.postgraphile = postgraphql(pgConfig, schema, postGraphileOptions);
} else {
this.postgraphile = postgraphql(pgConfig, postGraphileOptions);
}
app.use(this.postgraphile);
if (playground) {
app.get('/playground', expressPlayground({ endpoint: '/graphql' }));
}
}
}
}
const httpAdapter = this.httpAdapterHost.httpAdapter;
if (!httpAdapter) {
return;
}
const app = httpAdapter.getInstance();
// Break out PostGraphile options
const {pgConfig, schema, playground, ...postGraphileOptions} = this.options;
if (schema) {
this.postgraphile = postgraphql(pgConfig, schema, postGraphileOptions);
} else {
this.postgraphile = postgraphql(pgConfig, postGraphileOptions);
}
app.use(this.postgraphile);
if (playground) {
app.get('/playground', expressPlayground({ endpoint: '/graphql' }));
}
}
}
export default async function startApp(options = {}) {
const app = new Koa();
app.use(requestLogger(logger));
app.use(handleErrors(options));
const pgqlOpts = setPGQLOpts(options);
const pgPool = createPgPool(options, pgqlOpts);
await startSchemaWatcher(pgPool, 'public', pgqlOpts);
app.use(postgraphile(pgPool, 'public', pgqlOpts));
app.use(cors());
app.use(bodyParser());
app.use(cookie());
// load any user defined middleware
const middleware = load('middleware', { options, default: () => {} });
if (middleware.default) {
middleware.default({ app, logger, options });
}
app.use(appManifest(options));
if (!options.disableWebpack) {
// eslint-disable-next-line global-require
await require('../config/webpack.dev').default(app, options);
}
module.exports = async function performQuery(
pgPool,
schema,
query,
variables,
operationName
) {
const queryString = typeof query === "string" ? query : print(query);
return withPostGraphileContext({ pgPool }, async context =>
graphql(
schema, // The schema from `createPostGraphileSchema`
queryString,
null,
{ ...context }, // You can add more to context if you like
variables,
operationName
)
);
};