Skip to content

Commit

Permalink
feat(): allow registering global field middleware functions
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Jan 22, 2021
1 parent c451529 commit 773d5d8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
6 changes: 6 additions & 0 deletions lib/interfaces/build-schema-options.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { GraphQLDirective, GraphQLScalarType } from 'graphql';
import { FieldMiddleware } from './field-middleware.interface';

export type DateScalarMode = 'isoDate' | 'timestamp';
export type NumberScalarMode = 'float' | 'integer';
Expand Down Expand Up @@ -45,4 +46,9 @@ export interface BuildSchemaOptions {
* GraphQL schema directives mapping
*/
schemaDirectives?: Record<string, any>;

/**
* Array of global field middleware functions
*/
fieldMiddleware?: FieldMiddleware[];
}
13 changes: 8 additions & 5 deletions lib/schema-builder/factories/object-type-definition.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export class ObjectTypeDefinitionFactory {
options,
field.options,
);
const resolve = this.createFieldResolver(field);
const resolve = this.createFieldResolver(field, options);

fields[field.schemaName] = {
type,
Expand Down Expand Up @@ -174,12 +174,15 @@ export class ObjectTypeDefinitionFactory {
TContext = {},
TArgs = { [argName: string]: any },
TOutput = any
>(field: PropertyMetadata) {
>(field: PropertyMetadata, options: BuildSchemaOptions) {
const rootFieldResolver = (root: object) => {
const value = root[field.name];
return typeof value === 'undefined' ? field.options.defaultValue : value;
};
if (!field.middleware || field.middleware?.length === 0) {
const middlewareFunctions = (options.fieldMiddleware || []).concat(
field.middleware || [],
);
if (middlewareFunctions?.length === 0) {
return rootFieldResolver;
}

Expand All @@ -199,10 +202,10 @@ export class ObjectTypeDefinitionFactory {
index = currentIndex;
let middlewareFn: FieldMiddleware;

if (currentIndex === field.middleware.length) {
if (currentIndex === middlewareFunctions.length) {
middlewareFn = () => rootFieldResolver(root);
} else {
middlewareFn = field.middleware[currentIndex];
middlewareFn = middlewareFunctions[currentIndex];
}

let tempResult: TOutput = undefined;
Expand Down

0 comments on commit 773d5d8

Please sign in to comment.