Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"pg-minify": "^0.4.1",
"pluralize": "^3.0.0",
"postgres-interval": "^1.0.2",
"require-glob": "^3.2.0",
"send": "^0.14.1",
"tslib": "^1.5.0"
},
Expand Down
2 changes: 2 additions & 0 deletions src/graphql/schema/BuildToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ interface BuildToken {
// If true then the default mutations for tables (e.g. createMyTable) will
// not be created
readonly disableDefaultMutations: boolean,
// Path to read shcema injections from
readonly schemaInjection: string,
},
// Hooks for adding custom fields/types into our schema.
readonly _hooks: _BuildTokenHooks,
Expand Down
3 changes: 3 additions & 0 deletions src/graphql/schema/createGqlSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export type SchemaOptions = {
// GraphQL types that override the default type generation. Currently this
// API is private. Use at your own risk.
_typeOverrides?: _BuildTokenTypeOverrides,
// The path to read our injections from
schemaInjection?: string,
}

/**
Expand All @@ -36,6 +38,7 @@ export default function createGqlSchema (inventory: Inventory, options: SchemaOp
nodeIdFieldName: options.nodeIdFieldName || 'nodeId',
dynamicJson: options.dynamicJson || false,
disableDefaultMutations: options.disableDefaultMutations || false,
schemaInjection: options.schemaInjection || '',
},
_hooks: options._hooks || {},
_typeOverrides: options._typeOverrides || new Map(),
Expand Down
3 changes: 2 additions & 1 deletion src/graphql/schema/getMutationGqlType.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GraphQLObjectType, GraphQLFieldConfig } from 'graphql'
import { buildObject, memoize1 } from '../utils'
import { buildObject, memoize1, loadInjections } from '../utils'
import BuildToken from './BuildToken'
import createCollectionMutationFieldEntries from './collection/createCollectionMutationFieldEntries'

Expand Down Expand Up @@ -38,6 +38,7 @@ function createMutationGqlType (buildToken: BuildToken): GraphQLObjectType | und
.map(collection => createCollectionMutationFieldEntries(buildToken, collection))
.reduce((a, b) => a.concat(b), [])
),
...(loadInjections(options.schemaInjection, 'mutation')),
]

// If there are no mutation fields, just return to avoid errors.
Expand Down
4 changes: 3 additions & 1 deletion src/graphql/schema/getQueryGqlType.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GraphQLObjectType, GraphQLFieldConfig, GraphQLNonNull, GraphQLID } from 'graphql'
import { buildObject, memoize1 } from '../utils'
import { buildObject, memoize1, loadInjections } from '../utils'
import createNodeFieldEntry from './node/createNodeFieldEntry'
import getNodeInterfaceType from './node/getNodeInterfaceType'
import createCollectionQueryFieldEntries from './collection/createCollectionQueryFieldEntries'
Expand Down Expand Up @@ -36,6 +36,8 @@ function createGqlQueryType (buildToken: BuildToken): GraphQLObjectType {
.getCollections()
.map(collection => createCollectionQueryFieldEntries(buildToken, collection))
.reduce((a, b) => a.concat(b), []),
// Load injections
loadInjections(options.schemaInjection, 'query'),
[
// The root query type is useful for Relay 1 as it limits what fields
// can be queried at the top level.
Expand Down
3 changes: 2 additions & 1 deletion src/graphql/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import formatName from './formatName'
import idSerde from './idSerde'
import scrib from './scrib'
import parseGqlLiteralToValue from './parseGqlLiteralToValue'
import loadInjections from './loadInjections'

export { buildObject, formatName, idSerde, scrib, parseGqlLiteralToValue }
export { buildObject, formatName, idSerde, scrib, parseGqlLiteralToValue, loadInjections }

export * from './memoize'
54 changes: 54 additions & 0 deletions src/graphql/utils/loadInjections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* A utility function for requiring all files in a provided directory
* Returns an array of double dimensions, as expected by mutationEntries
*/

import { GraphQLFieldConfig } from 'graphql'
import postgraphql from '../../postgraphql/postgraphql'
const requireGlob = require('require-glob')

let initialized = false
const queries: Array<[string, GraphQLFieldConfig<never, mixed>]> = []
const mutations: Array<[string, GraphQLFieldConfig<never, mixed>]> = []

// Sync method to read the injections, populates our injections array
function initInjections(dirToInject: string): void {

const files: Array<{ type: string, name: string, schema: (object: {}) => GraphQLFieldConfig<never, mixed> }> = []

requireGlob.sync(dirToInject, {
cwd: process.cwd(),
reducer (_options: {}, tree: {} , file: {exports: { type: string, name: string, schema: (object: {}) => GraphQLFieldConfig<never, mixed>}}): {} {
files.push({type: file.exports.type, name: file.exports.name, schema: file.exports.schema})
return tree
},
})

// Resolve each injection to get schema and validate type.
files.forEach(file => {

if (file.type === 'query') {
queries.push([file.name, file.schema(postgraphql)])
} else if (file.type === 'mutation') {
mutations.push([file.name, file.schema(postgraphql)])
} else {
throw new Error(`Invalid type '${file.type}' in injection named ${file.name}.`)
}
})

initialized = true
}

export default function loadInjections(dirToInject: string, type: string): Array<[string, GraphQLFieldConfig<never, mixed>]> {

if (dirToInject === '' ) {
return []
}

if (!initialized) {
initInjections(dirToInject)
}

return type === 'query' ? queries : mutations

}
3 changes: 3 additions & 0 deletions src/postgraphql/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ program
.option('--export-schema-json [path]', 'enables exporting the detected schema, in JSON format, to the given location. The directories must exist already, if the file exists it will be overwritten.')
.option('--export-schema-graphql [path]', 'enables exporting the detected schema, in GraphQL schema format, to the given location. The directories must exist already, if the file exists it will be overwritten.')
.option('--show-error-stack [setting]', 'show JavaScript error stacks in the GraphQL result errors')
.option('--schema-injection [path]', 'requires the files in the specified path and injects them into the GraphQL schema (supports glob\'s)')

program.on('--help', () => console.log(`
Get Started:
Expand Down Expand Up @@ -80,6 +81,7 @@ const {
exportSchemaGraphql: exportGqlSchemaPath,
showErrorStack,
bodySizeLimit,
schemaInjection,
// tslint:disable-next-line no-any
} = program as any

Expand Down Expand Up @@ -124,6 +126,7 @@ const server = createServer(postgraphql(pgConfig, schemas, {
exportJsonSchemaPath,
exportGqlSchemaPath,
bodySizeLimit,
schemaInjection,
}))

// Start our server by listening to a specific port and host name. Also log
Expand Down
1 change: 1 addition & 0 deletions src/postgraphql/postgraphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type PostGraphQLOptions = {
exportGqlSchemaPath?: string,
bodySizeLimit?: string,
pgSettings?: { [key: string]: mixed },
schemaInjection?: string,
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/postgraphql/schema/createPostGraphQLSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export default async function createPostGraphQLSchema (
jwtSecret?: string,
jwtPgTypeIdentifier?: string,
disableDefaultMutations?: boolean,
schemaInjection?: string,
} = {},
): Promise<GraphQLSchema> {
// Create our inventory.
Expand Down Expand Up @@ -109,6 +110,7 @@ export default async function createPostGraphQLSchema (
nodeIdFieldName: options.classicIds ? 'id' : 'nodeId',
dynamicJson: options.dynamicJson,
disableDefaultMutations: options.disableDefaultMutations,
schemaInjection: options.schemaInjection,

// If we have a JWT Postgres type, let us override the GraphQL output type
// with our own.
Expand Down
7 changes: 4 additions & 3 deletions src/postgraphql/withPostGraphQLContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ export default async function withPostGraphQLContext(

return await callback({
[$$pgClient]: pgClient,
pgRole,
pgRole: pgRole.role,
jwtClaims: pgRole.jwtClaims,
})
}
// Cleanup our Postgres client by ending the transaction and releasing
Expand Down Expand Up @@ -104,7 +105,7 @@ async function setupPgClientTransaction ({
jwtAudiences?: Array<string>,
pgDefaultRole?: string,
pgSettings?: { [key: string]: mixed },
}): Promise<string | undefined> {
}): Promise<{role: string | undefined, jwtClaims: {} | undefined}> {
// Setup our default role. Once we decode our token, the role may change.
let role = pgDefaultRole
let jwtClaims: { [claimName: string]: mixed } = {}
Expand Down Expand Up @@ -180,7 +181,7 @@ async function setupPgClientTransaction ({
await pgClient.query(query)
}

return role
return {role, jwtClaims}
}

const $$pgClientOrigQuery = Symbol()
Expand Down