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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"homepage": "https://github.com/Tada5hi/rapiq#readme",
"dependencies": {
"@ucast/core": "^1.10.2",
"hookable": "^5.5.3",
"smob": "^1.5.0"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions src/parser/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/

import { DEFAULT_ID } from '../constants';
import type { Schema } from '../schema';
import { SchemaRegistry, defineSchema } from '../schema';
Expand Down
30 changes: 17 additions & 13 deletions src/parser/parameters/fields/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@
*/

import { isObject } from 'smob';
import type { ObjectLiteral } from '../../../types';
import { BaseParser } from '../../base';
import { DEFAULT_ID } from '../../../constants';
import {
FieldOperator, FieldsSchema, Schema, defineFieldsSchema,
FieldOperator, FieldsHookName, FieldsSchema, Schema, defineFieldsSchema,
} from '../../../schema';
import { DEFAULT_ID } from '../../../constants';
import { extractSubRelations } from '../../../schema/parameter/relations/helpers';
import type { ObjectLiteral } from '../../../types';
import { applyMapping, groupArrayByKeyPath, isPathAllowed } from '../../../utils';
import { BaseParser } from '../../base';
import { FieldsParseError } from './error';
import {
applyMapping, groupArrayByKeyPath, isPathAllowed,
} from '../../../utils';
import type { FieldsParseInputTransformed, FieldsParseOptions, FieldsParseOutput } from './types';
import { extractSubRelations } from '../../../schema/parameter/relations/helpers';

export class FieldsParser extends BaseParser<
FieldsParseOptions,
Expand Down Expand Up @@ -45,6 +43,8 @@ FieldsParseOutput
delete normalized[schema.name];
}

await schema.hooks.callHook(FieldsHookName.PARSE_NORMALIZED, normalized, options.context || {});

const data = normalized[DEFAULT_ID] || [];
delete normalized[DEFAULT_ID];

Expand Down Expand Up @@ -131,21 +131,25 @@ FieldsParseOutput
}
}

const keys = Object.keys(normalized);
await schema.hooks.callHook(FieldsHookName.PARSE_AFTER, output, options.context || {});

const normalizedKeys = Object.keys(normalized);

if (options.relations) {
await schema.hooks.callHook(FieldsHookName.PARSE_RELATIONS, options.relations, options.context || {});

for (let i = 0; i < options.relations.length; i++) {
const index = keys.indexOf(options.relations[i]);
const index = normalizedKeys.indexOf(options.relations[i]);
if (index === -1) {
keys.push(options.relations[i]);
normalizedKeys.push(options.relations[i]);
normalized[options.relations[i]] = [];
}
}
}

const grouped : Record<string, Record<string, any>> = {};
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
for (let i = 0; i < normalizedKeys.length; i++) {
const key = normalizedKeys[i];

let group : string;
let relation : string;
Expand Down
3 changes: 2 additions & 1 deletion src/parser/parameters/fields/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ export type FieldsParseOptions<
> = {
relations?: RelationsParseOutput,
schema?: string | Schema<RECORD> | FieldsSchema<RECORD>,
isChild?: boolean
isChild?: boolean,
context?: Record<string, any>
};
30 changes: 29 additions & 1 deletion src/schema/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,43 @@
* view the LICENSE file that was distributed with this source code.
*/

import type { HookCallback, HookKeys, Hookable } from 'hookable';
import { createHooks } from 'hookable';
import type { BaseSchemaOptions } from './types';

export class BaseSchema<OPTIONS extends BaseSchemaOptions = BaseSchemaOptions> {
type HookInferCallback<HT, HN extends keyof HT> = HT[HN] extends HookCallback
? HT[HN]
: never;

export class BaseSchema<
OPTIONS extends BaseSchemaOptions = BaseSchemaOptions,
HOOKS extends Record<string, any> = Record<string, HookCallback>,
> {
protected options: OPTIONS;

public readonly hooks: Hookable<HOOKS>;

// ---------------------------------------------------------

constructor(options: OPTIONS) {
this.options = options;
this.hooks = createHooks<HOOKS>();
}

// --------------------------------------------------

hook<NAME extends HookKeys<HOOKS>>(
name: NAME,
fn:HookInferCallback<HOOKS, NAME>,
) : CallableFunction {
return this.hooks.hook(name, fn);
}

hookOnce<NAME extends HookKeys<HOOKS>>(
name: NAME,
fn:HookInferCallback<HOOKS, NAME>,
) : CallableFunction {
return this.hooks.hookOnce(name, fn);
}

// ---------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/schema/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class Schema<
this.extendSchemaOptions(this.sort);
}

private extendSchemaOptions(schema: BaseSchema<any>) {
private extendSchemaOptions(schema: BaseSchema<any, any>) {
if (
typeof this.options.throwOnFailure !== 'undefined' &&
typeof schema.throwOnFailure === 'undefined'
Expand Down
6 changes: 6 additions & 0 deletions src/schema/parameter/fields/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@ export enum FieldOperator {
INCLUDE = '+',
EXCLUDE = '-',
}

export enum FieldsHookName {
PARSE_NORMALIZED = 'parse:normalized',
PARSE_AFTER = 'parse:after',
PARSE_RELATIONS = 'parse:relations',
}
7 changes: 3 additions & 4 deletions src/schema/parameter/fields/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ import type { ObjectLiteral, SimpleKeys } from '../../../types';
import {
isPropertyNameValid,
} from '../../../utils';
import type { FieldsOptions } from './types';
import type { FieldsHooks, FieldsOptions } from './types';
import { BaseSchema } from '../../base';

export class FieldsSchema<
RECORD extends ObjectLiteral = ObjectLiteral,
CONTEXT extends ObjectLiteral = ObjectLiteral,
> extends BaseSchema<FieldsOptions<RECORD, CONTEXT>> {
> extends BaseSchema<FieldsOptions<RECORD>, FieldsHooks> {
public default : string[];

public defaultIsUndefined : boolean;
Expand All @@ -28,7 +27,7 @@ export class FieldsSchema<

// ---------------------------------------------------------

constructor(input: FieldsOptions<RECORD, CONTEXT> = {}) {
constructor(input: FieldsOptions<RECORD> = {}) {
super(input);

this.allowed = [];
Expand Down
26 changes: 21 additions & 5 deletions src/schema/parameter/fields/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,31 @@
* view the LICENSE file that was distributed with this source code.
*/

import type { BaseSchemaOptions, VerifyFn } from '../../types';
import type { ObjectLiteral, SimpleKeys } from '../../../types';
import type { BaseSchemaOptions } from '../../types';
import type { ObjectLiteral, ObjectLiteralKeys, SimpleKeys } from '../../../types';
import type { FieldsHookName } from './constants';

export type FieldsOptions<
T extends Record<string, any> = Record<string, any>,
CONTEXT extends ObjectLiteral = ObjectLiteral,
> = BaseSchemaOptions & {
mapping?: Record<string, string>,
allowed?: SimpleKeys<T>[],
default?: SimpleKeys<T>[],
verify?: VerifyFn<string[], CONTEXT>
default?: SimpleKeys<T>[]
};

export type FieldsHooks = ObjectLiteralKeys<{
[FieldsHookName.PARSE_NORMALIZED]: (
value: Record<string, string[]>,
context: ObjectLiteral
) => Promise<void> | void;

[FieldsHookName.PARSE_AFTER]: (
value: string[],
context: ObjectLiteral
) => Promise<void> | void,

[FieldsHookName.PARSE_RELATIONS]: (
value: string[],
context: ObjectLiteral
) => Promise<void> | void,
}>;
8 changes: 0 additions & 8 deletions src/schema/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,6 @@ export type BaseSchemaOptions = {
schemaMapping?: Record<string, string>
};

export type VerifyFn<
VALUE = unknown,
CONTEXT extends Record<PropertyKey, any> = Record<string, any>,
> = (
value: VALUE,
context: CONTEXT
) => Promise<VALUE>;

export type SchemaOptionsNormalized<
RECORD extends ObjectLiteral = ObjectLiteral,
> = BaseSchemaOptions & {
Expand Down
50 changes: 50 additions & 0 deletions test/unit/parser/fields-hook.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2025.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/

import { FieldsParser, defineSchema } from '../../../src';
import { registry } from '../../data/schema';

describe('parser/fields/hooks', () => {
let parser: FieldsParser;

beforeAll(() => {
parser = new FieldsParser(registry);
});

it('should work with hook: parse:normalized', async () => {
const schema = defineSchema({});
schema.fields.hook('parse:normalized', () => {});

const output = await parser.parse(['foo'], { schema });
expect(output).toEqual(['foo']);

expect(schema.fields.hooks._hooks['parse:normalized']).toBeDefined();
});

it('should work with parse:after hook', async () => {
const schema = defineSchema({});
schema.fields.hook('parse:after', (data) => {
data.push('bar');
});

const output = await parser.parse(['foo'], { schema });
expect(output).toEqual(['foo', 'bar']);
});

it('should work with parse:relations hook', async () => {
const schema = registry.getOrFail('user');
schema.fields.hook('parse:relations', (data) => {
data.push('realm');
});

const output = await parser.parse(['id', 'realm.name'], { schema, relations: [] });
expect(output).toEqual([
'id',
'realm.name',
]);
});
});