Custom options
There are many use cases where you want to add your own options to the FieldOptions
or the EntityOptions
and have them available in that Entity's metadata.
You can do that using Typescript Module Augmentation
To demo that, let's say that we want to have a custom placeholderText
options to be set in the Field decorator, and later used in our UI.
Follow these Steps:
- In a typescript file that is visible throughout your project add the following code:tsThis will add the optional
declare module 'remult' { export interface FieldOptions<entityType, valueType> { placeholderText?: string } }
placeholderText
property to theFieldOptions
interface - In your entity, set the
placeholderText
value.tsimport { Entity, Fields } from "remult"; @Entity("tasks", { allowApiCrud: true }) export class Task { @Fields.uuid() id!: string; @Fields.string({ placeholderText:'Please enter a task title' }) title = ''; @Fields.boolean() completed = false; }
- Use that property in your UIhtml
<input placeholder={taskRepo.metadata.fields.title.options.placeholderText}/>
Augmenting UserInfo
interface
If you want to have more information in remult.user
you can augment the UserInfo
interface
declare module 'remult' {
export interface UserInfo {
phone:string,
email:string
}
}
Then later in the code, you can use it just like any other UserInfo
property
console.log(remult.user.phone);
Augmenting remult's context
property
You can augment remult's context property in a similar way:
declare module 'remult' {
export interface RemultContext {
// anything you want
}
}
One use case for this, is to include information from the request, and use that information in an entity or a backend method.
Here's an example:
- Add a custom property
origin
toRemultContext
tsdeclare module 'remult' { export interface RemultContext { origin?: string } }
- Set the
origin
property in theinitRequest
method in theapi.ts
file.tsexport const api = remultExpress({ initRequest: async (_, req) => { remult.context.origin = req.headers.origin; }, entities: [Task], //...
- Use it anywhere in the code:tsor
@BackendMethod({ allowed: Roles.admin }) static async doSomethingImportant() { console.log(remult.context.origin); }
ts@Entity<Task>("tasks", { saving:task=>{ task.lastUpdateDate = new Date(); task.lastUpdateUser = remult.user?.name; task.lastUpdateOrigin = remult.context.origin; }, //...
For more info see the Augmenting Global Properties article in vue.js
docs.