Where should I create data models?


#1

Hey guys,

This is probably a beginner question, I’ve recently started trying out Ionic 3 (and Angular) and I’m not too sure where I should keep my “models”?

I’m trying to define a custom class, I was thinking to create the class as a provider. Then I read somewhere the providers are used as DI services, in my case, it’s really just a data model with some helper functions.

Thanks


#2

I have found “just a data model with some helper functions” to be a generally bad fit for the JavaScript world. I have had better luck with smart providers and dumb data, so I would do something like this:

export interface Customer {
  id: string;
  name: string;
}

export interface Purchase {
  id: string;
  customerId: string;
  productId: string;
  quantity: number;
}

@Injectable()
export class Provider {
  constructor(private _http: Http) {}

  customerById(id: string): Observable<Customer> {
    return this._http.get('/api/customer/' + id).map(rsp => rsp.json());
  }

  purchasesByCustomer(id: string): Observable<Purchase[]> {
    return this._http.get('/api/purchases?customer=' + id).map(rsp => rsp.json().purchases);
  }
}

EDIT: I don’t know if it’s still a problem, but due to previous security concerns about naked JSON arrays, I always make my APIs return objects with a single array member instead of a raw array. Edited purchasesByCustomer() to reflect that.


#3

Thanks, it looks promising I’ll give it a try.


#4

I use interfaces too, but I’ve found the following helps. I have a models folder with defining interface and useful constants that can be exported as needed. Example: WidgetsModel:

export interface Widget {
   id: string;
   photoURL: string;
   type: WidgetType;
}

export type WidgetType= bigWidget,
                        smallWidget,
                        undefined;

export const widgetInitialState = {
                                   id = '',
                                   photoURL: imagePlaceHolder,
                                   type: WidgetType.undefined
                                  }
export const imagePlaceHolder = //dataURI of a small image placeholder

#5

Generic warning about how const in JavaScript is less than worthless, because somebody can mess with your head like so:

let widget = widgetInitialState;
widget.id = 'ruh roh';

And now we’ve poisoned widgetInitialState. Because of this, I use functions here instead:

export function widgetInitialState() {
  return {
    id = '',
    photoURL: imagePlaceHolder,
    type: WidgetType.undefined
  };
}