Skip to content
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adobe/plugin-hooks",
"version": "0.3.5",
"version": "0.3.6",
"publishConfig": {
"access": "public"
},
Expand Down
9 changes: 6 additions & 3 deletions src/afterAllExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
GraphQLData,
GraphQLError as GraphQLErrorType,
GraphQLResult,
StateApi,
} from './types';
import type { YogaLogger, GraphQLParams } from 'graphql-yoga';
import { PLUGIN_HOOKS_ERROR_CODES } from './errorCodes';
Expand All @@ -28,10 +29,11 @@ export interface AfterAllExecutionContext {
body: unknown;
headers: Record<string, string>;
secrets: Record<string, string>;
state: StateApi;
logger: YogaLogger;
document: unknown;
result: { data?: GraphQLData; errors?: GraphQLErrorType[] };
setResultAndStopExecution: (result: GraphQLResult) => void;
logger: YogaLogger;
afterAll: HookConfig;
}

Expand All @@ -45,17 +47,18 @@ export async function executeAfterAllHook(
body,
headers,
secrets,
state,
logger,
document,
result,
setResultAndStopExecution,
logger,
afterAll,
} = context;

try {
// Create payload with the execution result
const payload = {
context: { params, request, body, headers, secrets },
context: { params, request, body, headers, secrets, state, logger },
document,
result, // This is the GraphQL execution result
};
Expand Down
8 changes: 6 additions & 2 deletions src/beforeAllExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ governing permissions and limitations under the License.

import { GraphQLError } from 'graphql/error';
import getBeforeAllHookHandler, { UpdateContextFn } from './handleBeforeAllHooks';
import type { HookConfig, MemoizedFns, GraphQLResult } from './types';
import type { HookConfig, MemoizedFns, GraphQLResult, StateApi } from './types';
import type { YogaLogger, GraphQLParams } from 'graphql-yoga';
import { PLUGIN_HOOKS_ERROR_CODES } from './errorCodes';

Expand All @@ -22,6 +22,8 @@ export interface BeforeAllExecutionContext {
body: unknown;
headers: Record<string, string>;
secrets: Record<string, string>;
state: StateApi;
logger: YogaLogger;
document: unknown;
updateContext: UpdateContextFn;
setResultAndStopExecution: (result: GraphQLResult) => void;
Expand All @@ -37,14 +39,16 @@ export async function executeBeforeAllHook(
body,
headers,
secrets,
state,
logger,
document,
updateContext,
setResultAndStopExecution,
} = context;

try {
const payload = {
context: { params, request, body, headers, secrets },
context: { params, request, body, headers, secrets, state, logger },
document,
};
await beforeAllHookHandler({ payload, updateContext });
Expand Down
6 changes: 6 additions & 0 deletions src/errorCodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export const PLUGIN_HOOKS_ERROR_CODES = {
/** Error during beforeAll hook execution */
ERROR_PLUGIN_HOOKS_BEFORE_ALL: 'ERROR_PLUGIN_HOOKS_BEFORE_ALL',

/** Error during beforeSource hook execution */
ERROR_PLUGIN_HOOKS_BEFORE_SOURCE: 'ERROR_PLUGIN_HOOKS_BEFORE_SOURCE',

/** Error during afterSource hook execution */
ERROR_PLUGIN_HOOKS_AFTER_SOURCE: 'ERROR_PLUGIN_HOOKS_AFTER_SOURCE',

/** Error during afterAll hook execution */
ERROR_PLUGIN_HOOKS_AFTER_ALL: 'ERROR_PLUGIN_HOOKS_AFTER_ALL',
} as const;
Expand Down
93 changes: 69 additions & 24 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ OF ANY KIND, either express or implied. See the License for the specific languag
governing permissions and limitations under the License.
*/

import { GraphQLError } from 'graphql/error';
import { UpdateContextFn } from './handleBeforeAllHooks';
import { createBeforeAllHookHandler, executeBeforeAllHook } from './beforeAllExecutor';
import { createAfterAllHookHandler, executeAfterAllHook } from './afterAllExecutor';
import type {
import {
HookConfig,
MemoizedFns,
UserContext,
GraphQLData,
GraphQLError as GraphQLErrorType,
SourceHookConfig,
StateApi,
PLUGIN_HOOKS_ERROR_CODES,
} from './types';
import getBeforeSourceHookHandler from './handleBeforeSourceHooks';
import type { YogaLogger, Plugin, YogaInitialContext } from 'graphql-yoga';
Expand Down Expand Up @@ -80,6 +83,9 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
try {
const { beforeAll, afterAll, beforeSource, afterSource, baseDir, logger } = config;

// Unchanging server context
const serverContext: Partial<UserContext> = {};

// Check if any hooks are configured
const hasAnyHooks = beforeAll || afterAll || beforeSource || afterSource;
if (!hasAnyHooks) {
Expand All @@ -88,6 +94,7 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
onFetch: async () => {},
};
}

const memoizedFns: MemoizedFns = {
afterSource: {},
beforeSource: {},
Expand All @@ -105,6 +112,9 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
const { params, request } = context || {};
const headers = Object.fromEntries(request.headers.entries());
const secrets = ('secrets' in context ? context.secrets : {}) as Record<string, string>;
const state = ('state' in context ? context.state : {}) as StateApi;
serverContext.secrets = secrets;
serverContext.state = state;
let body = {};
if (request && request.body) {
body = request.body;
Expand Down Expand Up @@ -143,6 +153,8 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
body,
headers,
secrets,
state,
logger,
document,
updateContext,
setResultAndStopExecution,
Expand All @@ -166,10 +178,11 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
body,
headers,
secrets,
state,
logger,
document,
result,
setResultAndStopExecution,
logger,
afterAll: afterAll!,
});
},
Expand Down Expand Up @@ -199,17 +212,33 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
memoizedFns,
});

const payload = {
request: options,
operation: info.operation,
sourceName,
};
try {
const payload = {
context: {
secrets: serverContext.secrets!,
state: serverContext.state!,
logger,
},
request: options,
operation: info.operation,
sourceName,
};

await beforeSourceHookHandler({
payload,
hookType: 'beforeSource',
sourceName,
});
await beforeSourceHookHandler({
payload,
hookType: 'beforeSource',
sourceName,
});
} catch (err: unknown) {
throw new GraphQLError(
(err instanceof Error && err.message) || 'Error while executing beforeSource hook',
{
extensions: {
code: PLUGIN_HOOKS_ERROR_CODES.ERROR_PLUGIN_HOOKS_BEFORE_SOURCE,
},
},
);
}
}
return async ({
response,
Expand All @@ -224,18 +253,34 @@ export default async function hooksPlugin(config: PluginConfig): Promise<HooksPl
logger,
memoizedFns,
});
const payload = {
request: options,
operation: info.operation,
sourceName,
response,
setResponse,
};
await afterSourceHookHandler({
payload,
hookType: 'afterSource',
sourceName,
});
try {
const payload = {
context: {
secrets: serverContext.secrets!,
state: serverContext.state!,
logger,
},
request: options,
operation: info.operation,
sourceName,
response,
setResponse,
};
await afterSourceHookHandler({
payload,
hookType: 'afterSource',
sourceName,
});
} catch (err: unknown) {
throw new GraphQLError(
(err instanceof Error && err.message) || 'Error while executing afterSource hook',
{
extensions: {
code: PLUGIN_HOOKS_ERROR_CODES.ERROR_PLUGIN_HOOKS_AFTER_SOURCE,
},
},
);
}
};
},
};
Expand Down
27 changes: 27 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,35 @@ export type GraphQLResult = {
errors?: GraphQLError[];
};

/**
* State API interface for managing key-value pairs.
*/
export interface StateApi {
/**
* Get a value by key.
* @param key Key to retrieve.
*/
get(key: string): Promise<string | null>;

/**
* Put a key-value pair with optional TTL.
* @param key Key to store.
* @param value Value to store.
* @param config Optional configuration object that may contain a TTL value in seconds.
*/
put(key: string, value: string, config?: { ttl?: number }): Promise<void>;

/**
* Delete a key-value pair.
* @param key
*/
delete(key: string): Promise<void>;
}

export interface UserContext extends YogaInitialContext {
headers?: Record<string, string>;
secrets?: Record<string, string>;
state?: StateApi;
}

export type SourceHookConfig = Record<string, HookConfig[]>;
Expand Down Expand Up @@ -72,6 +98,7 @@ export interface PayloadContext {
body: unknown;
headers?: Record<string, string>;
secrets?: Record<string, string>;
state?: StateApi;
}

export type HookFunction = (
Expand Down
Loading