@continutech/sd-angular-jsonapi v1.0.13
Skyline Dynamics - JSON API - Angular 5 Implementation
This documentation is still a work in progress, Pull Requests are welcome :)
Table Of Contents
- Installation
- Configuration
- Resources Creating resources Entity Manager Instantiating a resource Fetch all resources Fetch a single resource Fetch all resources (or a single one) including related data Filter a request Paginate a request Filter resource fields Create new resources * Update existing resources
- Collections .reset() .all() .get() .first() .last() .filter() .find() .findLast() .findIndex() .sortBy() .each() .forEach() .every() .includes() .chunk() .indexOf() .nth() .at() .atIndex() .slice() .add() .remove() .tail() .take() * .takeRight()
- Error Handling
- Road Map
Installation
Install the library with the following command:
npm install --save @continutech/sd-angular-jsonapi
or
yarn add @continutech/sd-angular-jsonapi
Add the Module to your app.module.ts
file:
@NgModule({
imports: [
...
SDJsonApiModule.forRoot()
],
})
Configuration
The Module can be configured by injecting the EntityManager
in any component (can be the AppComponent)
and calling the .configure()
method.
constructor(private entityManager: EntityManager){
entityManager.configure(
{
baseUrl: 'http://yourdomain.com',
version: 'v1'
});
}
The following configuration options are available:
Variable | Required | Type | Default Value | Description |
---|---|---|---|---|
baseUrl | Yes | string | empty | The root URL of your API |
version | No | string | empty | The version identified of your API. If ommitted, no version will be used. Can be any string like 'v1' or '1' |
Resources
Creating resources
To create a resource, create a class that extends from JSONAPIResource
and decorate it with the @JSONAPI()
decorator
@JSONAPI()
export class Author extends JSONAPIResource{
}
optionally you can define attributes on the class that should be returned by the API. Note that these attributes are only to enable type-hinting in compatible IDE's. The attributes will not actually be used to define the data that will be returned from the API.
EntityManager
The EntityManager
is the central service for creating and destroying resources.
Resources stored will be kept between components, and can be refreshed or destroyed.
Instantiating a resource
Instantiate a resource by requesting it from the EntityManager
.
A resource can only be instantiated if it extends the JSONAPIResource
class.
const author = this.entityManager.createResource(Author);
That's it!
Fetch all resources
To fetch all entries of a certain resource, you can call the .all()
method, or optionally the .get()
method without parameters.
So
author.all();
is the same as
author.get();
Calling the .all()
or .get()
method on a resource returns an Observable of type Collection
that will contain the results of the API call
// TODO error handling is not implemented yet, but if an API call fails, it should return a properly typed ErrorResult
Example for a full call:
// Define the Resource
@JSONAPI()
export class Author extends JSONAPIResource{
}
//Instantiate the resource
const authors = this.entityManager.createResource(Author);
//Get all authors
authors.all().subscribe(
(successResult: Collection) => {
console.log('Loaded the following authors from the API: ' + successResult.all());
},
(errorResult) => {
console.log('Whoops, something went wrong!');
});
Fetch a single resource
To fetch a single resource, simply call the .get()
method on the resource and provide the ID of the resource you'd like to fetch:
// Define the Resource
@JSONAPI()
export class Author extends JSONAPIResource{
}
//Instantiate the resource
const authors = this.entityManager.createResource(Author);
//Get author with the ID 23
authors.get(23).subscribe(
(successResult: Collection) => {
console.log('Loaded the following author from the API: ' + successResult.first());
},
(errorResult) => {
console.log('Whoops, something went wrong!');
});
Note that, even though we're requesting a single resource, at this time the library will still return a full collection (which only contains the author we requested).
Alternatively, you can use the .find()
method to retrieve a resource by ID.
The difference between .find()
and .get()
is, that .get()
called without parameters behaves like .all()
.
Calling .find()
without a parameter will throw an Error.
Fetch all resources (or a single one) including related data
// TODO
Filter a request
You can filter a resource by using the .filter()
and .filters()
methods on the resource.
Note that filters need to be applied BEFORE sending the request, so BEFORE you call .all()
, .get()
or .find()
// Define the Resource
@JSONAPI()
export class Author extends JSONAPIResource{
}
//Instantiate the resource
const authors = this.entityManager.createResource(Author);
//Get all authors that are still alive
authors.filter('alive',true).all().subscribe(
(successResult: Collection) => {
console.log('Loaded the following authors from the API: ' + successResult.all());
},
(errorResult) => {
console.log('Whoops, something went wrong!');
});
Paginate a request
// TODO
Filter resource fields (Sparse Fieldsets)
Currently, this implementation only supports filtering fields on the current resource, not on included or lazy-loaded relationship resources.
To add a filter to the request, simply call the .fields()
method:
Note that filters need to be applied BEFORE sending the request, so BEFORE you call .all()
, .get()
or .find()
.only()
is available as an alias method with the same parameter signature
// Define the Resource
@JSONAPI()
export class Author extends JSONAPIResource{
}
//Instantiate the resource
const authors = this.entityManager.createResource(Author);
//Get all authors but only retrieve the 'name', 'alive' and 'date_of_birth' attributes
authors.fields(['name','alive','date_of_birth']).all().subscribe(
(successResult: Collection) => {
console.log('Loaded the following authors from the API: ' + successResult.all());
},
(errorResult) => {
console.log('Whoops, something went wrong!');
});
Create new resources
// TODO
Update existing resources
To update an existing resource, simply call the .update()
method after you modified the corresponding fields:
// Define the Resource
@JSONAPI()
export class Author extends JSONAPIResource{
}
//Instantiate the resource
const authors = this.entityManager.createResource(Author);
//Retrieve all authors and update the first one
authors.all().subscribe(
(successResult: Collection) => {
console.log('Loaded the following authors from the API: ' + successResult.all());
const author = successResult.first();
author.name = 'My Awesome Name';
author.update().subscribe(
(updateSuccess: Collection) => {
},
(updateError) => {
console.log('Whoops, something went wrong!');
}
)
},
(errorResult) => {
console.log('Whoops, something went wrong!');
});
Delete existing resources
// TODO
Deletion of related resources
// TODO
Attaching relationship resources
// TODO
Automatically creating and attaching relationship resources
// TODO
Detaching relationship resources
// TODO
Automatically deleting and detaching relationship resources
// TODO
Collections
Collections are a way to bundle results, they behave very similar to an Array
type, but have some useful additional functions:
.reset()
Parameters: None
Returns:
Collection<T>
Example: TODO
.all(asOriginal: boolean = false)
Parameters:
Parameter | Type | Default Value |
---|---|---|
asOriginal | boolean | false |
Returns:
Array
Example: TODO
.get(asOriginal: boolean = false)
Parameters:
Parameter | Type | Default Value |
---|---|---|
asOriginal | boolean | false |
Returns:
Array
Example: TODO
.first()
Parameters: None
Returns:
JSONAPIResource<T>
or {}
Example: TODO
.last()
Parameters: None
Returns:
JSONAPIResource<T>
or {}
Example: TODO
.filter(predicate: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
predicate | any | N/A |
Returns:
Collection<T>
Example: TODO
.find(predicate: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
predicate | any | N/A |
Returns:
Collection<T>
Example: TODO
.findLast(predicate: any, index: number = this.elements.length - 1)
Parameters:
Parameter | Type | Default Value |
---|---|---|
predicate | any | N/A |
index | number | Length of the Collection - 1 |
Returns:
Collection<T>
Example: TODO
.findIndex(predicate: any, fromIndex: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
predicate | any | N/A |
fromIndex | number | 0 |
Returns:
number
or undefined
Example: TODO
.sortBy(iteratees: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
iteratees | any | N/A |
Returns:
Collection<T>
Example: TODO
.each(callback: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
callback | any | N/A |
Returns:
Collection<T>
Example: TODO
.forEach(callback: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
callback | any | N/A |
Returns:
Collection<T>
Example: TODO
.every(predicate: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
predicate | any | N/A |
Returns:
boolean
Example: TODO
.includes(value: any, fromIndex: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
value | any | N/A |
fromIndex | number | 0 |
Returns:
boolean
Example: TODO
.chunk(size: number = 1)
Parameters:
Parameter | Type | Default Value |
---|---|---|
size | number | 1 |
Returns:
Collection<T>
Example: TODO
.indexOf(value: any, fromIndex: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
value | any | N/A |
fromIndex | number | 0 |
Returns:
number
or undefined
Example: TODO
.nth(index: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
index | number | 0 |
Returns:
JSONAPIResource<T>
or {}
Example: TODO
.at(index: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
index | number | 0 |
Returns:
JSONAPIResource<T>
or {}
Example: TODO
.atIndex(index: number = 0)
Parameters:
Parameter | Type | Default Value |
---|---|---|
index | number | 0 |
Returns:
JSONAPIResource<T>
or {}
Example: TODO
.slice(start: number = 0, end: number = this.elements.length)
Parameters:
Parameter | Type | Default Value |
---|---|---|
start | number | 0 |
end | number | Length of the Collection |
Returns:
Collection<T>
Example: TODO
.add(element: any)
Parameters:
Parameter | Type | Default Value |
---|---|---|
element | any | N/A |
Returns:
Collection<T>
Example: TODO
.remove(element?: any, index?: number)
Parameters:
Parameter | Type | Default Value |
---|---|---|
element | any | N/A |
index | number | N/A |
Returns:
Collection<T>
Example: TODO
.tail()
Parameters: None
Returns:
Collection<T>
Example: TODO
.take(amount: number = 1)
Parameters:
Parameter | Type | Default Value |
---|---|---|
amount | number | 1 |
Returns:
Collection<T>
Example: TODO
.takeRight(amount: number = 1)
Parameters:
Parameter | Type | Default Value |
---|---|---|
amount | number | 1 |
Returns:
Collection<T>
Example: TODO
Error Handling
In case a request did not return the expected results, this library will return either a default
HttpErrorResponse or a JSONAPIErrorBag
.
The error bag contains an array of JSONAPIErrorResponse
:
export declare class JSONAPIErrorBag {
errors: JSONAPIErrorResponse[];
constructor(errors: JSONAPIErrorResponse[]);
list(): JSONAPIErrorResponse[];
}
export declare class JSONAPIErrorResponse {
id: JSONAPIErrorID;
links: JSONAPIErrorLinks;
status: number;
code: JSONAPIErrorCode;
title: string;
detail: string;
source: JSONAPIErrorSource;
meta: any;
constructor(error: IJSONAPIErrorResponse);
}
Errors are ALWAYS emitted through Observables, so make sure you have a corresponding callback in place.
Road Map
- Resource Creation and Instantiation
- Fetching resources
- Fetch all resources
- Fetch single resource
- Fetch single resource with relationship(s)
- Fetch all resources with relationship(s)
- Filter resources
- Create new resources
- Attach relationships
- Create and attach resource/relationship
- Detach relationships
- Delete and detach resource/relationship
- Update existing resources
- Delete existing resources
- Paginate resources
- Filter resource fields
- Lazy-load relationships
- Refresh Resources
- Error Handling