canjscanjs-model

Option to specify base server url for can.Model?


Is there a way to specify the base url for can.Model?

I see the server path being hard coded this way:

Wine = can.Model({
    findAll : 'GET //localhost/Cellar-CanJS-Bootstrapped/api/wines',
    findOne : 'GET //localhost/Cellar-CanJS-Bootstrapped/api/wines/{id}',
    create  : 'POST //localhost/Cellar-CanJS-Bootstrapped/api/wines',
    update  : 'PUT //localhost/Cellar-CanJS-Bootstrapped/api/wines/{id}',
    destroy : 'DELETE //localhost/Cellar-CanJS-Bootstrapped/api/wines/{id}'
},{
})

What I'm looking for is a way specify the base url for the Model so that I can continue to configure my can.Model is the standard way.


Solution

  • Unfortunately setting a model base URL is not a built in feature yet but planned for the next minor release. This is how I usually do it at the moment:

    function getUrl(url, method) {
        method = method || 'GET';
        return method + ' ' + BASE_URL + '/' + url;
    }
    
    Wine = can.Model({
        findAll : getUrl('api/wines');
        findOne : getUrl('api/wines/{id}'),
        create  : getUrl('api/wines', 'POST'),
        update  : getUrl('wines/{id}', 'PUT'),
        destroy : getUrl('api/wines/{id}', 'DELETE')
    },{
    });
    

    getUrl can be a Model static method or located in a better spot (e.g. application bootstrap) as well.