Page MenuHomeSealhub

props-parser.ts
No OneTemporary

Authored By
Unknown
Size
1 KB
Referenced Files
None
Subscribers
None

props-parser.ts

import { Shape } from "@sealcode/ts-predicates";
import { BaseContext } from "koa";
import merge from "merge";
import { FormData, FormDataValue } from "..";
import { BasePageProps } from "./list";
export type EncodedProps = Record<string, unknown>;
// page props parser is only tasked with getting the raw props from *somewhere*
// and being able to put new values back to that somewhere. Parsing to numbers
// or any other exotic types is done by fields logic.
export abstract class PagePropsParser<PropsType> {
abstract decode(ctx: BaseContext): Record<string, FormDataValue>;
abstract encode(props: Record<string, FormData>): EncodedProps;
abstract getHTMLInputName(prop_name: string): string;
constructor(
public propsShape: Shape,
public defaultValues: Partial<PropsType>
) {}
overwriteProp(
ctx: BaseContext,
new_props: Partial<PropsType>
): EncodedProps {
const result = {};
merge.recursive(result, this.decode(ctx), new_props);
return result;
}
makeHiddenInputs(values: PropsType, fields_to_skip: string[]): string {
return Object.entries(values)
.filter(([key]) => !fields_to_skip.includes(key))
.map(
([key, value]: [string, string | number]) => /* HTML */ `<input
type="hidden"
name="${key}"
value="${value}"
/>`
)
.join(" ");
}
getDefaultValue<Key extends keyof PropsType>(
key: Key
): PropsType[Key] | undefined {
return this.defaultValues[key];
}
}
export class AllQueryParams<
PropsType extends BasePageProps
> extends PagePropsParser<PropsType> {
decode(ctx: BaseContext): Record<string, FormDataValue> {
const query = {
...this.defaultValues,
...ctx.query,
};
return query;
}
encode(props: PropsType): Record<string, unknown> {
return props;
}
getHTMLInputName(prop_name: string): string {
return prop_name;
}
}

File Metadata

Mime Type
application/javascript
Expires
Fri, Nov 27, 17:39 (1 d, 13 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1220766
Default Alt Text
props-parser.ts (1 KB)

Event Timeline