7

Is it possible to create a js-data resource definition using a TypeScript class?

What I would like in general is having full typing support on computed property and instance method definitions.

What would be awesome is something like this:

class SomeModel
{
    public someBusinessModelValue = 'foo';
    public someMoreValues = 'bar';

    public get someComputedProperty()
    {
        return this.someBusinessModelValue + someMoreValues;
    }

    public instanceMethod(param: string)
    {
        return this.someMoveValues.search(param);
    }
}

and then

DS.defineResource(fromClass('name', '/endpoint', 'idAttr', SomeModel));

or go even further and define it like

class SomeModelStore extends SomeModel
{
    name = 'name';
    endpoint = 'endpoint';
    idAttribute = 'idAttr';
    relations = 
    {
        //[...]
    }
}

and use it like

DS.defineResource(SomeModelStore);

Note that these are only some thoughts on what I hope it would look like, I am aware that it does probably not work exactly like that.

Aides
  • 3,643
  • 5
  • 23
  • 39

1 Answers1

5

JSData 2.x

The answer is yes, somewhat. Creating Resource definitions in JSData 2.x is not very flexible, but you can provide a constructor function (via the useClass option) to be used during record instantiation.

Here is an example: http://plnkr.co/edit/vNCoC8?p=info and the useClass documentation: http://www.js-data.io/docs/dsdefaults#useclass

JSData 3.x

In JSData 3.x you can just extend the various classes:

import { DataStore, Mapper, Record } from 'js-data';

class CustomMapper extends Mapper {
  // ...
}

const store = new DataStore({
  mapperClass: CustomMapper
});

class BaseCustomRecord extends Record {
  // ...  
}

store.defineMapper('user', {
  recordClass: class UserRecord extends BaseCustomRecord { /*...*/ }
});
store.defineMapper('post', {
  recordClass: class PostRecord extends BaseCustomRecord { /*...*/ }
});
store.defineMapper('comment', {
  recordClass: class CommentRecord extends BaseCustomRecord { /*...*/ }
});

// etc. etc.

Here are some plunker that show extending some classes with JSData 3.x:

And the API docs are a handy resource when extending classes: http://api.js-data.io/js-data/latest/index.html

jdobry
  • 1,041
  • 6
  • 17
  • 1
    Is there any way to have one custom class for each mapper in a single store ? – khamaileon Feb 22 '17 at 00:01
  • Does this also work with schema validation? http://www.js-data.io/v3.0/docs/validation mentions extending the Schema class but it's not documented yet. – Aides Mar 28 '17 at 10:53