DEV Community

Discussion on: TypeScript Functional Decorators w/ usecases

Collapse
 
akashkava profile image
Akash Kava

At Web Atoms, we are using decorator as follow,

Bindable Property


   @BindableProperty
   public value: any;

This turns member into property with getter/setter with ability to refresh the UI whenever it is set.

Dependency Injection


   @Inject
   public userService: UserService;

DI container automatically injects service for specified type.

Watch Decorator


   @Watch
   public get fullName() {
       return `${this.model.firstName} ${this.model.lastName}`;
   }

Full name property automatically freshes the UI bound to this property when firstName or lastName changes.

Validation

   @Validate
   public get errorFirstName() {
       return this.model.firstName ? "" : "First name is required";
   }

Validate decorator helps in setting up validation that updates UI automatically when property is changed.

AJAX Services

@DISingleton()
@BaseUrl("/api/v2020/app/")
export default class TaskService extends BaseService {

    @Get("user")
    public getUser(): Promise<IUser>;

    @Get("tasks")
    public getTasks(
        @Query("search") search: string,
        // default value should be specified in
        // decorator and not in argument declaration
        @Query("status", "open") status?: string
    ): Promise<ITask[]>

    @Get("tasks/{id}/attachments")
    public getAttachments(
        @Path("id") id: number
    ): Promise<ITaskAttachment[]>;

    @Put("tasks")
    public createTask(@Body task: ITask): Promise<ITask>;

    @Post("tasks/{id}/attachments")
    public uploadAttachment(
        @Path("id") id: number,
        @Body att: IAttachment,
        cancelToken: CancelToken): Promise<void>;
}

Data Loading

This is a bit complex, it handles loading of data and canceling previous request automatically.

   @Load({ watch: true })
   public async loadData(ct: CancelToken) {
        const search = this.search;
        this.list = await this.userService.loadUsers(search, ct);
   }

So whenever search is updated, this method is called automatically and UI refreshes it, it discards (aborts) previous ongoing request.

For more information...

Collapse
 
radnerus profile image
Suren

Interesting implementations, Akash!