Commit d4965799 authored by Guillaume Perréal's avatar Guillaume Perréal
Browse files

metadata.ts: expose ResourceType et getResourceMetadata mais cache METADATA.

parent dec00e5b
......@@ -55,7 +55,12 @@ export interface Metatypes {
/**
* Type des clefs de Metatypes.
*/
type ResourceType = keyof Metatypes;
export type ResourceType = keyof Metatypes;
/**
* Type des instances d'une ressource de type R.
*/
export type ResourceModel<T extends ResourceType> = Metatypes[T]['resource'];
/**
* Metadonnées d'une propriété d'une ressource.
......@@ -157,7 +162,7 @@ export class ParametrizedIRIMetadata<R extends Resource, P extends any[]> extend
* T : valeur de la propriété '@type', e.g. 'Person'.
* R : type de resource, e.g. Person
*/
export class ResourceMetadata<T extends ResourceType, R extends Resource> {
export class ResourceMetadata<T extends ResourceType, R extends Resource = ResourceModel<T>> {
private readonly properties = {} as { [N in keyof R]: PropertyMetadata<R>; };
public constructor(
......@@ -228,7 +233,7 @@ export class ResourceMetadata<T extends ResourceType, R extends Resource> {
*/
{% for repo in repositories %}
export const {{ repo.resourceName }}Metadata = new ResourceMetadata<'{{ repo.resourceName }}', {{ repo.resourceName }}>(
export const {{ repo.resourceName }}Metadata = new ResourceMetadata<'{{ repo.resourceName }}'>(
'{{ repo.resourceName }}',
'{{ repo.identifier.name }}',
[ {% for type in repo.atTypes -%}{{ type.usage }},{% endfor %} ],
......@@ -265,20 +270,30 @@ export const {{ repo.resourceName }}Metadata = new ResourceMetadata<'{{ repo.res
/**
* Dictionnaire des metadonnées.
*/
export const METADATA: { readonly [N in ResourceType]: ResourceMetadata<N, Metatypes[N]['resource']> } = {
const METADATA: { [T in ResourceType]: ResourceMetadata<T> } = {
{% for repo in repositories %}
{{ repo.resourceName }}: {{ repo.resourceName }}Metadata,
{% endfor %}
};
/**
* Typeguard pour un type de resource T (e.g. 'Person').
* Recupère les métadonnées d'un type de ressource.
*/
export function isResourceOfType<T extends ResourceType>(that: any, type: T): that is Metatypes[T]['resource'] {
export function getResourceMetadata<T extends ResourceType>(type: T): ResourceMetadata<T> {
if (typeof type !== 'string') {
throw new Error(`Resource type must be a string, got ${typeof type}`);
}
if (!(type in METADATA)) {
throw new Error(`Unknown resource type "${type}"`);
}
return METADATA[type].isResource(that);
return METADATA[type] as any;
}
/**
* Typeguard pour un type de resource T (e.g. 'Person').
*/
export function isResourceOfType<T extends ResourceType>(that: any, type: T): that is ResourceModel<T> {
return getResourceMetadata(type).isResource(that);
}
/**
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment