npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gethint/ngx-jsonapi

v1.0.17

Published

JSON API library for Angular

Downloads

10

Readme

ngx-jsonapi

angular jsonapi

CircleCI Codacy Badge npm version Coverage Status

Online demo

You can test library on this online example 👌 http://ngx-jsonapi.reyesoft.com/.

demo app

Data is obtained from Json Api Playground server.

Supported features

  • Cache (on memory): TTL for collections and resources. Before a HTTP request objects are setted with cached data.
  • Cache on IndexedDB
  • Pagination
  • Sorting
  • Include param support (also, when you save)
  • Equal requests, return a same ResourceObject on memory
  • Default values for a new resource (hydrator).

Migration

Usage

Just install, configure and learn with examples.

First of all, it's advisable to read Jsonapi specification. Understanding JsonApi documents structure is recommended.

Installation

yarn add [email protected] --save
# or npm if you wish...

Dependecies and customization

  1. Add Jsonapi dependency.
  2. Configure your url and other paramemeters.
  • Angular
/* .. */
import { NgxJsonapiModule } from 'ngx-jsonapi';

@NgModule()
export class AppModule {
    public constructor() {
        JsonapiBootstrap.bootstrap({
            user_config: { url: '//jsonapiplayground.reyesoft.com/v2/' }
        });
    }
}
  • React
import { NgxJsonapiModule } from 'ngx-jsonapi';

const App = () => {
    JsonapiBootstrap.bootstrap({
        user_config: { url: '//jsonapiplayground.reyesoft.com/v2/' }
    });

    return <div>Hello world</div>;
};

Enable Local Cache

Library cache anything memory. With Local Store, also store all on IndexDb on browser. Faster apps when we reuse a lot of data.

  • Angular
/* .. */
import { NgxJsonapiModule, StoreService, JsonRipper } from 'ngx-jsonapi';

@NgModule()
export class AppModule {
    public constructor() {
        JsonapiBootstrap.bootstrap({
            user_config: { url: '//jsonapiplayground.reyesoft.com/v2/' },
            jsonapiStore: new StoreService(),
            jsonRipper: new JsonRipper()
        });
    }
}
  • React
import { NgxJsonapiModule } from 'ngx-jsonapi';

const App = () => {
    JsonapiBootstrap.bootstrap({
        user_config: { url: '//jsonapiplayground.reyesoft.com/v2/' },
        jsonapiStore: new StoreService(),
        jsonRipper: new JsonRipper()
    });

    return <div>Hello world</div>;
};

Examples

Like you know, the better way is with examples. Lets go! 🚀

Defining a resource

authors.service.ts

import { Injectable } from '@angular/core';
import { Autoregister, Service, Resource, DocumentCollection, DocumentResource } from 'ngx-jsonapi';
import { Book } from '../books/books.service';
import { Photo } from '../photos/photos.service';

export class Author extends Resource {
    public attributes = {
        name: 'default name',
        date_of_birth: ''
    };

    public relationships = {
        books: new DocumentCollection<Book>(),
        photo: new DocumentResource<Photo>()
    };
}

@Injectable()
@Autoregister()
export class AuthorsService extends Service<Author> {
    public resource = Author;
    public type = 'authors';
}

Get a collection of resources

Controller

import { Component } from '@angular/core';
import { DocumentCollection } from 'ngx-jsonapi';
import { AuthorsService, Author } from './../authors.service';

@Component({
    selector: 'demo-authors',
    templateUrl: './authors.component.html'
})
export class AuthorsComponent {
    public authors: DocumentCollection<Author>;

    public constructor(private authorsService: AuthorsService) {
        authorsService
            .all({
                // include: ['books', 'photos'],
                // fields: {
                //     authors: ['name']
                // }
            })
            .subscribe(authors => (this.authors = authors));
    }
}

View for this controller

<p *ngFor="let author of authors.data; trackBy: authors.trackBy">
    id: {{ author.id }} <br />
    name: {{ author.attributes.name }} <br />
    birth date: {{ author.attributes.date_of_birth | date }}
</p>

Collection sort

Example: name is a authors attribute, and makes a query like /authors?sort=name,job_title

let authors = authorsService.all({
    sort: ['name', 'job_title']
});

Collection filtering

Filter resources with attribute: value values. Filters are used as 'exact match' (only resources with attribute value same as value are returned). value can also be an array, then only objects with same attribute value as one of values array elements are returned.

authorsService.all({
    remotefilter: { country: 'Argentina' }
});

Get a single resource

From this point, you only see important code for this library. For a full example, clone and see demo directory.

authorsService.get('some_author_id');

More options? Include resources when you fetch data (or save!)

authorsService.get('some_author_id', { include: ['books', 'photos'] });

TIP: these parameters work with all() and save() methods too.

Add a new resource

let author = this.authorsService.new();
author.attributes.name = 'Pablo Reyes';
author.attributes.date_of_birth = '2030-12-10';
author.save();

Need you more control and options?

let author = this.authorsService.new();
author.attributes.name = 'Pablo Reyes';
author.attributes.date_of_birth = '2030-12-10';

// some_book is an another resource like author
let some_book = booksService.get(1);
author.addRelationship(some_book);

// some_publisher is a polymorphic resource named company on this case
let some_publisher = publishersService.get(1);
author.addRelationship(some_publisher, 'company');

// wow, now we need detach a relationship
author.removeRelationship('books', 'book_id');

// this library can send include information to server, for atomicity
author.save({ include: ['book'] });

// mmmm, if I need get related resources? For example, books related with author 1
let relatedbooks = booksService.all({ beforepath: 'authors/1' });

// you need get a cached object? you can force ttl on get
let author$ = authorsService.get(
    'some_author_id',
    { ttl: 60 } // ttl on seconds (default: 0)
);

Update a resource

authorsService.get('some_author_id').suscribe(author => {
    this.author.attributes.name += 'New Name';
    this.author.save(success => {
        console.log('author saved!');
    });
});

Pagination

authorsService.all({
  // get page 2 of authors collection, with a limit per page of 50
  page: { number: 2 ;  size: 50 }
});

Collection page

  • number: number of the current page
  • size: size of resources per page (it's sended to server by url)
  • information returned from server (check if is avaible) total_resources: total of avaible resources on server resources_per_page: total of resources returned per page requested

Local Demo App

You can run JsonApi Demo App locally following the next steps:

git clone [email protected]:reyesoft/ngx-jsonapi.git
cd ngx-jsonapi
yarn
yarn start

We use as backend Json Api Playground.

Colaborate

Check Environment development file 😉.