Support `undefined`, `number` in JSON module by mario-campos · Pull Request #3980 · github/codeql-action · GitHub
Skip to content
Open
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
32 changes: 16 additions & 16 deletions lib/entry-points.js

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

33 changes: 28 additions & 5 deletions src/json/index.test.ts
31 changes: 29 additions & 2 deletions src/json/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ export function isString(value: unknown): value is string {
return typeof value === "string";
}

/** Asserts that `value` is a number. */
export function isNumber(value: unknown): value is number {
return typeof value === "number";
}

/** Asserts that `value` is either a string or undefined. */
export function isStringOrUndefined(
value: unknown,
Expand All @@ -55,8 +60,17 @@ export const string = {
required: true,
} as const satisfies Validator<string>;

/** Transforms a validator to be optional. */
export function optional<T>(validator: Validator<T>) {
/** A validator for number fields in schemas. */
export const number = {
validate: isNumber,
required: true,
} as const satisfies Validator<number>;
Comment on lines +63 to +67

/**
* Transforms a validator to be optional, accepting `undefined` or `null` for an
* absent value.
*/
export function optionalOrNull<T>(validator: Validator<T>) {
return {
validate: (val: unknown) => {
return val === undefined || val === null || validator.validate(val);
Expand All @@ -65,6 +79,19 @@ export function optional<T>(validator: Validator<T>) {
} as const satisfies Validator<T | undefined | null>;
}

/**
* Transforms a validator to be optional, accepting `undefined` for an absent
* value but, unlike `optionalOrNull`, rejecting `null`.
*/
export function optional<T>(validator: Validator<T>) {
return {
validate: (val: unknown): val is T | undefined => {
return val === undefined || validator.validate(val);
},
required: false,
} as const satisfies Validator<T | undefined>;
}

/** Represents an arbitrary object schema. */
export type Schema = Record<string, Validator<any>>;

Expand Down
16 changes: 8 additions & 8 deletions src/start-proxy/types.ts
Loading