Search code examples
javascripttypescriptjsdata

Define js-data resource in TypeScript


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.


Solution

  • 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