An Angular service for interaction with API's
You can install this package using yarn
or npm
:
#yarn
yarn add @meanie/angular-api
#npm
npm install @meanie/angular-api --save
Include the script node_modules/@meanie/angular-api/release/angular-api.js
in your build process, or add it via a <script>
tag to your index.html
:
<script src="node_modules/@meanie/angular-api/release/angular-api.js"></script>
Add Api.Service
as a dependency for your app.
angular.module('App', [
'Api.Service'
]).config(function($apiProvider, App) {
//Set API wide base URL
//Defaults to /
$apiProvider.setBaseUrl(App.api.baseUrl);
//Set the default actions for each endpoint, or empty for none
//Defaults as given here:
$apiProvider.setDefaultActions({
query: {
method: 'GET',
isArray: true,
isModel: true
},
get: {
method: 'GET',
isModel: true
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
delete: {
method: 'DELETE'
}
});
//Set the default params for each endpoint, or empty for none
//Defaults as given here:
$apiProvider.setDefaultParams({
id: '@id'
});
//Set the default model to use for each endpoint
//Defaults to none
$apiProvider.setDefaultModel('$baseModel');
//Strip trailing slashes behavior
//Defaults to true
$apiProvider.stripTrailingSlashes(false);
});
Register new endpoints in the config function of your modules, for example:
angular.module('App.Users').config(function($apiProvider) {
$apiProvider.registerEndpoint('users', {
model: 'User',
actions: {
me: {
url: 'me/',
isModel: true
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
exists: {
method: 'POST',
url: 'exists/'
}
}
});
});
Available options for endpoint configuration are:
The base URL defaults to the API base URL, but you can specify a different base URL for a specific endpoint, for example if connecting to a 3rd party URL.
The url part of an endpoint defaults to its name, but you can override it by specifying a custom url.
Name of the service to use for JSON to model conversion.
A hash of actions with the action name/accessor as keys and the action config as values.
Action specific configuration will override global endpoint configuration. Available action configuration options are listed below. Any additional/unknown configuration options that you supply will be passed on to the $http
service when doing the actual request.
The url part of an action defaults to /
, but you can specify a different URL. It will be concatenated to the endpoint URL.
Specify the action HTTP request method, defaults to GET
.
Name of the service to use for JSON to model conversion.
Specify whether the action expects an array as a response, defaults to false
.
Specify whether the received JSON data should be converted to a model, defaults to false
. When isArray
is true
, it will convert each object in the array to a model.
Specify a custom success response interceptor for the action.
Specify a custom error response interceptor for the action.
You can create custom models and expose API actions from within them. It is recommended to use the supplied $baseModel
service as a base for your own models, as it comes with handy to/from JSON converters.
/**
* Module definition and dependencies
*/
angular.module('App.User.Model', [
'Api.Service',
'BaseModel.Service'
])
/**
* Model definition
*/
.factory('User', function($api, $baseModel) {
//Default data
let defaultData = {
name: 'Guest'
};
/**
* Constructor
*/
function User(data) {
$baseModel.call(this, data);
}
/**
* Extend prototype
*/
angular.extend(User.prototype, $baseModel.prototype);
/**
* Save user
*/
User.prototype.save = function(data) {
//Extend instance data with optionally given extra data
data = this.toJSON(data);
//Determine method and call API
let method = this.id ? 'update' : 'create';
return $api.user[method](data).then(data => this.fromJSON(data));
};
//Return
return User;
});
//The endpoints return promises which resolve into models
let users = $api.users.query(); //An array of UserModel instances
//You can also interact with the model and modify it before resolving
let user = $api.users.create({name: 'Meanie'}).then(user => {
user.doSomething();
});
//Interact with exposed API actions through the model methods
let myUser = new User({
name: 'Meanie'
});
myUser.save().then(user => {
myUser === user; //User and myUser are the same class instance
});
Please report any bugs, issues, suggestions and feature requests in the @meanie/angular-api issue tracker.
Pull requests are welcome! If you would like to contribute to Meanie, please check out the Meanie contributing guidelines.
This package has been kindly sponsored by Hello Club, an all in one club and membership management solution complete with booking system, automated membership renewals, online payments and integrated access and light control. Check us out if you happen to belong to any kind of club or if you know someone who helps run a club!
(MIT License)
Copyright 2015-2020, Adam Reis