1.0.13 • Published 7 years ago

@continutech/sd-angular-jsonapi v1.0.13

Weekly downloads
1
License
MIT
Repository
gitlab
Last release
7 years ago

Skyline Dynamics - JSON API - Angular 5 Implementation

This documentation is still a work in progress, Pull Requests are welcome :)

Table Of Contents

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:

VariableRequiredTypeDefault ValueDescription
baseUrlYesstringemptyThe root URL of your API
versionNostringemptyThe 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().all().get().first().last()
.filter().find().findLast().findIndex().sortBy()
.each().forEach().every().includes().chunk
.indexOf.nth().at().atIndex().slice()
.add().remove().tail().take().takeRight()

.reset()

Parameters: None

Returns: Collection<T>

Example: TODO

.all(asOriginal: boolean = false)

Parameters:

ParameterTypeDefault Value
asOriginalbooleanfalse

Returns: Array

Example: TODO

.get(asOriginal: boolean = false)

Parameters:

ParameterTypeDefault Value
asOriginalbooleanfalse

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:

ParameterTypeDefault Value
predicateanyN/A

Returns: Collection<T>

Example: TODO

.find(predicate: any)

Parameters:

ParameterTypeDefault Value
predicateanyN/A

Returns: Collection<T>

Example: TODO

.findLast(predicate: any, index: number = this.elements.length - 1)

Parameters:

ParameterTypeDefault Value
predicateanyN/A
indexnumberLength of the Collection - 1

Returns: Collection<T>

Example: TODO

.findIndex(predicate: any, fromIndex: number = 0)

Parameters:

ParameterTypeDefault Value
predicateanyN/A
fromIndexnumber0

Returns: number or undefined

Example: TODO

.sortBy(iteratees: any)

Parameters:

ParameterTypeDefault Value
iterateesanyN/A

Returns: Collection<T>

Example: TODO

.each(callback: any)

Parameters:

ParameterTypeDefault Value
callbackanyN/A

Returns: Collection<T>

Example: TODO

.forEach(callback: any)

Parameters:

ParameterTypeDefault Value
callbackanyN/A

Returns: Collection<T>

Example: TODO

.every(predicate: any)

Parameters:

ParameterTypeDefault Value
predicateanyN/A

Returns: boolean

Example: TODO

.includes(value: any, fromIndex: number = 0)

Parameters:

ParameterTypeDefault Value
valueanyN/A
fromIndexnumber0

Returns: boolean

Example: TODO

.chunk(size: number = 1)

Parameters:

ParameterTypeDefault Value
sizenumber1

Returns: Collection<T>

Example: TODO

.indexOf(value: any, fromIndex: number = 0)

Parameters:

ParameterTypeDefault Value
valueanyN/A
fromIndexnumber0

Returns: number or undefined

Example: TODO

.nth(index: number = 0)

Parameters:

ParameterTypeDefault Value
indexnumber0

Returns: JSONAPIResource<T> or {}

Example: TODO

.at(index: number = 0)

Parameters:

ParameterTypeDefault Value
indexnumber0

Returns: JSONAPIResource<T> or {}

Example: TODO

.atIndex(index: number = 0)

Parameters:

ParameterTypeDefault Value
indexnumber0

Returns: JSONAPIResource<T> or {}

Example: TODO

.slice(start: number = 0, end: number = this.elements.length)

Parameters:

ParameterTypeDefault Value
startnumber0
endnumberLength of the Collection

Returns: Collection<T>

Example: TODO

.add(element: any)

Parameters:

ParameterTypeDefault Value
elementanyN/A

Returns: Collection<T>

Example: TODO

.remove(element?: any, index?: number)

Parameters:

ParameterTypeDefault Value
elementanyN/A
indexnumberN/A

Returns: Collection<T>

Example: TODO

.tail()

Parameters: None

Returns: Collection<T>

Example: TODO

.take(amount: number = 1)

Parameters:

ParameterTypeDefault Value
amountnumber1

Returns: Collection<T>

Example: TODO

.takeRight(amount: number = 1)

Parameters:

ParameterTypeDefault Value
amountnumber1

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
1.0.13

7 years ago

1.0.12

7 years ago

1.0.11

7 years ago

1.0.10

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.1

7 years ago