1
0
mirror of https://github.com/devcode-it/openstamanager.git synced 2025-02-25 07:47:55 +01:00

81 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-10-11 19:57:42 +02:00
import {
type PluralResponse,
Model as BaseModel
2021-10-11 19:57:42 +02:00
} from 'coloquent';
import {snakeCase} from 'lodash';
2022-01-07 16:04:50 +01:00
export interface InstantiableModel<T extends Model> {
new (): Model | T;
}
2022-01-07 16:04:50 +01:00
export type IModel<T extends Model = Model> = InstanceType<InstantiableModel<T>>;
/**
* The base model for all models.
*/
export abstract class Model extends BaseModel {
jsonApiType: string = '';
2022-01-07 16:04:50 +01:00
[prop: string]: any;
constructor() {
super();
// Return a proxy of this object to allow dynamic attributes getters and setters
// eslint-disable-next-line no-constructor-return, @typescript-eslint/no-unsafe-return
return new Proxy(this, {
get(target, property: string, receiver): any {
const snakeCasedProperty = snakeCase(property);
if (snakeCasedProperty in target.getAttributes()) {
return target.getAttribute(snakeCasedProperty);
}
return Reflect.get(target, property, receiver);
},
set(target, property: string, value) {
target.setAttribute(snakeCase(property), value);
return true;
}
});
}
/**
* Just an alias to the get() method.
*
* Returns all the instances of the model.
*/ // @ts-ignore
static all(): Promise<PluralResponse<InstanceType<Model>>> {
// @ts-ignore
return this.get();
}
setAttributes(attributes: Record<string, any>): void {
2021-10-08 16:49:17 +02:00
for (const [attribute, value] of Object.entries(attributes)) {
this.setAttribute(attribute, value);
2021-10-08 16:49:17 +02:00
}
}
getAttribute(attributeName: string): any {
return super.getAttribute(attributeName);
}
setAttribute(attributeName: string, value: any) {
super.setAttribute(attributeName, value);
}
getAttributes(): {[p: string]: any} {
return super.getAttributes();
}
getJsonApiBaseUrl(): string {
return '/api';
2021-09-29 20:29:08 +02:00
}
getJsonApiType(): string {
return (super.getJsonApiType() ?? snakeCase(this.constructor.name));
}
getId() {
return this.getApiId();
}
}