Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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 entitySchema = schema.entities[entityType];
const props: InputProps = {
source: attributeName,
};
if (entitySchema[attributeName].required) {
props.validate = [required()];
}
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>;
}