Newer
Older
import { InputProps, required } from "ra-core";
import { Schema, SchemaEntityTypes } from "./Schema";
type FormHelpers<S extends Schema> = {
[EntityType in SchemaEntityTypes<S>]: {
getInputProps: (attrName: keyof S["entities"][EntityType]) => InputProps;
};
};
export function createFormHelpers<S extends Schema>(schema: S): FormHelpers<S> {
type EntityAttributeNames<EntityType extends SchemaEntityTypes<S>> = Extract<
keyof S["entities"][EntityType],
string
>;
function getInputProps<EntityType extends SchemaEntityTypes<S>>(
entityType: SchemaEntityTypes<S>,
attributeName: EntityAttributeNames<EntityType>
) {
const attributeSchema = schema.entities[entityType][attributeName];
const props: InputProps = {
source: attributeName,
};
if (attributeSchema.required) {
props.validate = [required()];
}
if (attributeSchema.default !== undefined) {
props.initialValue = attributeSchema.default;
}
return props;
}
return Object.fromEntries(
(Object.keys(schema.entities) as SchemaEntityTypes<S>[]).map(
(entityType) => {
return [
entityType,
{
getInputProps: <EntityType extends SchemaEntityTypes<S>>(
attributeName: EntityAttributeNames<EntityType>
) => getInputProps(entityType, attributeName),
},
];
}
)
) as FormHelpers<S>;
}