Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4868

Is it possible to have polymorphic Ember Data Models?

$
0
0

Suppose I have the following model definitions:

// models/person.ts
import Model, { attr, hasMany, belongsTo } from '@ember-data/model';

enum Role {
  STUDENT = "STUDENT",
  TEACHER = "TEACHER",
}

export default class Person extends Model{
  @attr("string") declare name: string
  @attr("role") declare role: Role
  @attr("json") declare data: string
}

// models/student.ts
import Person from "./person"

export default  class Student extends Person {
   
  get clubMemberships(): string[] {
    return []
  }
}

// models/teacher.ts
import Person from "./person"

export default class Teacher extends Person {
   get officeHoursSchedule(): Date[]{
     
     return []
   }
}

Unfortunately, the Back-end I’m consuming only has one table called persons and this table stores all model specific data like office hours schedule and club memberships in a json field.

I want to be able to make a call to the persons table to get all the persons but then depending on the role of each returned person, I want to invoke a different model. Is this possible and is it even a valid ember data pattern?

So I’m thinking of something along these lines.

// adapters/person.ts
import RESTAdapter from '@ember-data/adapter/rest';
import PersonModel from "../models/person"

class Person extends RESTAdapter {
  async findAll(): EmberArray<TeacherModel | StudentModel | PersonModel>  {
    const url = this.buildURL('person', null);
    const res = await this.ajax(url, 'GET');

    const modified = {
      persons: res.persons.map(this.getModelFromRole),
    };
    return modified;
  }

  getModelFromRole(person: PersonModel){
    switch(person.role){
      case Role.STUDENT:
        return // invoke student model here
      case Role.TEACHER:
        return  // invoke teacher model here
      default:
        return  // invoke person model here
    }
  }
}

3 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 4868

Trending Articles