A maintained JSON:API adapter for Angular. Map resources and relationships to TypeScript models, with CRUD operations, dirty tracking, and rollback.
This project continues the work of nab-angular2-jsonapi, building on the original angular2-jsonapi library, with versioned releases for Angular 20, 21, and 22.
Choose the library major version that matches your Angular application. The current major version supports Angular 22.
| Angular | ngx-esy-jsonapi | npm tag |
|---|---|---|
| 22 | 22.x |
latest |
| 21 | 21.x |
angular21 |
| 20 | 20.x |
angular20 |
Open the live playground to try relationships, CRUD operations, dirty tracking, rollback, and JSON:API errors. The playground uses a local API simulation and resets edits when you refresh the page. Example source
From a clone of this repository:
npm ci
npm startOpen http://localhost:4200. The example README also describes how to publish the static build on GitHub Pages.
Migrating from nab-angular2-jsonapi or angular2-jsonapi? Start with the migration guide.
- Angular compatibility
- Try the example
- Introduction
- Installation
- Usage
- Development
- Maintenance and contributing
- Additional tools
- License
JSON:API responses describe resources, attributes, and relationships. ngx-esy-jsonapi maps those responses to TypeScript model instances so your Angular application can work with connected objects instead of manually resolving raw response data.
Use the datastore to query, create, update, and delete records, load related resources, and access records already in the store. Model instances track attribute changes and let you roll back unsaved changes.
For example, a post and its included comments become models connected through their relationships:
[
Post{
id: 1,
title: 'My post',
content: 'My content',
comments: [
Comment{
id: 1,
// ...
},
Comment{
id: 2,
// ...
}
]
},
// ...
]To install this library, run:
$ npm install ngx-esy-jsonapi --saveThis library uses reflected property types. Keep experimentalDecorators: true, emitDecoratorMetadata: true, and useDefineForClassFields: false in your application TypeScript configuration. Load reflect-metadata before your models. See the migration guide for the configuration and dependency setup.
For a standalone application, register provideHttpClient() and your datastore service. The example bootstrap and datastore show the complete setup. Use your own API URL and omit the example's mock interceptor.
For an NgModule application, add JsonApiModule to your app module imports:
import { JsonApiModule } from 'ngx-esy-jsonapi';
@NgModule({
imports: [
BrowserModule,
JsonApiModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }Firstly, create your Datastore service:
- Extend the
JsonApiDatastoreclass - Decorate it with
@JsonApiDatastoreConfig, set thebaseUrlfor your APIs and map your models (Optional: you can setapiVersion,baseUrlwill be suffixed with it) - Pass the
HttpClientdepencency to the parent constructor.
import { JsonApiDatastoreConfig, JsonApiDatastore, DatastoreConfig } from 'ngx-esy-jsonapi';
const config: DatastoreConfig = {
baseUrl: 'http://localhost:8000/v1/',
models: {
posts: Post,
comments: Comment,
users: User
}
}
@Injectable()
@JsonApiDatastoreConfig(config)
export class Datastore extends JsonApiDatastore {
constructor(http: HttpClient) {
super(http);
}
}Then set up your models:
- Extend the
JsonApiModelclass - Decorate it with
@JsonApiModelConfig, passing thetype - Decorate the class properties with
@Attribute - Decorate the relationships attributes with
@HasManyand@BelongsTo - (optional) Define your Metadata
import { JsonApiModelConfig, JsonApiModel, Attribute, HasMany, BelongsTo } from 'ngx-esy-jsonapi';
@JsonApiModelConfig({
type: 'posts'
})
export class Post extends JsonApiModel {
@Attribute()
title: string;
@Attribute()
content: string;
@Attribute({ serializedName: 'created-at' })
createdAt: Date;
@HasMany()
comments: Comment[];
}
@JsonApiModelConfig({
type: 'comments'
})
export class Comment extends JsonApiModel {
@Attribute()
title: string;
@Attribute()
created_at: Date;
@BelongsTo()
post: Post;
@BelongsTo()
user: User;
}
@JsonApiModelConfig({
type: 'users'
})
export class User extends JsonApiModel {
@Attribute()
name: string;
// ...
}Now, you can use your Datastore in order to query your API with the findAll() method:
- The first argument is the type of object you want to query.
- The second argument is the list of params: write them in JSON format, and they will be serialized.
- The returned value is a document that gives access to the metadata and the models.
// ...
constructor(private datastore: Datastore) { }
getPosts(){
this.datastore.findAll(Post, {
page: { size: 10, number: 1 },
filter: {
title: 'My Post',
},
}).subscribe(
(posts: JsonApiQueryData<Post>) => console.log(posts.getModels())
);
}Use peekAll() to retrieve all the records for a given type that are already loaded into the store, without making a network request:
let posts = this.datastore.peekAll(Post);Use findRecord() to retrieve a record by its type and ID:
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => console.log(post)
);Use peekRecord() to retrieve a record by its type and ID, without making a network request. This will return the record only if it is already present in the store:
let post = this.datastore.peekRecord(Post, '1');You can create records by calling the createRecord() method on the datastore:
- The first argument is the type of object you want to create.
- The second is a JSON with the object attributes.
this.datastore.createRecord(Post, {
title: 'My post',
content: 'My content'
});Making changes to records is as simple as setting the attribute you want to change:
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
post.title = 'New title';
}
);Records are persisted on a per-instance basis. Call save() on any instance of JsonApiModel and it will make a network request.
The library takes care of tracking the state of each record for you so that newly created records are treated differently from existing records when saving.
Newly created records will be POSTed:
let post = this.datastore.createRecord(Post, {
title: 'My post',
content: 'My content'
});
post.save().subscribe(); // => POST to '/posts'Records that already exist on the backend are updated using the HTTP PATCH verb:
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
post.title = 'New title';
post.save().subscribe(); // => PATCH to '/posts/1'
}
);The save() method will return an Observer that you need to subscribe:
post.save().subscribe(
(post: Post) => console.log(post)
);Note: always remember to call the subscribe() method, even if you are not interested in doing something with the response. Since the http method return a cold Observable, the request won't go out until something subscribes to the observable.
You can tell if a record has outstanding changes that have not yet been saved by checking its hasDirtyAttributes property.
At this point, you can either persist your changes via save() or you can roll back your changes. Calling rollbackAttributes() for a saved record reverts all the dirty attributes to their original value.
this.datastore.findRecord(Post, '1').subscribe(
(post: Post) => {
console.log(post.title); // => 'Old title'
console.log(post.hasDirtyAttributes); // => false
post.title = 'New title';
console.log(post.hasDirtyAttributes); // => true
post.rollbackAttributes();
console.log(post.hasDirtyAttributes); // => false
console.log(post.title); // => 'Old title'
}
);For deleting a record, call the datastore's method deleteRecord(), passing the type and the id of the record:
this.datastore.deleteRecord(Post, '1').subscribe(() => {
// deleted!
});To query an object including its relationships, you can pass in its options the attribute name you want to load with the relationships:
this.datastore.findAll(Post, {
page: { size: 10, number: 1},
include: 'comments'
}).subscribe(
(document) => {
console.log(document.getMeta()); // metadata
console.log(document.getModels()); // models
}
);The same if you want to include relationships when finding a record:
this.datastore.findRecord(Post, '1', {
include: 'comments,comments.user'
}).subscribe(
(post: Post) => console.log(post)
);The library will try to resolve relationships on infinite levels connecting nested objects by reference. So that you can have a Post, with a list of Comments, that have a User that has Posts, that have Comments... etc.
Note: If you include multiple relationships, do not use whitespaces in the include string (e.g. comments, comments.user) as those will be encoded to %20 and this results in a broken URL.
If the object you want to create has a one-to-many relationship, you can do this:
let post = this.datastore.peekRecord(Post, '1');
let comment = this.datastore.createRecord(Comment, {
title: 'My comment',
post: post
});
comment.save().subscribe();The library will do its best to discover which relationships map to one another. In the code above, for example, setting the comment relationship with the post will update the post.comments array, automatically adding the comment object!
If you want to include a relationship when creating a record to have it parsed in the response, you can pass the params object to the save() method:
comment.save({
include: 'user'
}).subscribe(
(comment: Comment) => console.log(comment)
);You can also update an object that comes from a relationship:
this.datastore.findRecord(Post, '1', {
include: 'comments'
}).subscribe(
(post: Post) => {
let comment: Comment = post.comments[0];
comment.title = 'Cool';
comment.save().subscribe((comment: Comment) => {
console.log(comment);
});
}
);Metadata such as links or data for pagination purposes can also be included in the result.
For each model a specific MetadataModel can be defined. To do this, the class name needs to be added in the ModelConfig.
If no MetadataModel is explicitly defined, the default one will be used, which contains an array of links and meta property.
@JsonApiModelConfig({
type: 'deals',
meta: JsonApiMetaModel
})
export class Deal extends JsonApiModel
An instance of a class provided in meta property will get the whole response in a constructor.
Datastore config can be specified through the JsonApiDatastoreConfig decorator and/or by setting a config variable of the Datastore class. If an option is specified in both objects, a value from config variable will be taken into account.
@JsonApiDatastoreConfig(config: DatastoreConfig)
export class Datastore extends JsonApiDatastore {
private customConfig: DatastoreConfig = {
baseUrl: 'http://something.com'
}
constructor() {
this.config = this.customConfig;
}
}config:
models- all the models which will be stored in the datastorebaseUrl- base API URLapiVersion- optional, a string which will be appended to the baseUrloverrides- used for overriding internal methods to achive custom functionalities
getDirtyAttributes- determines which model attributes are dirtytoQueryString- transforms query parameters to a query string
@JsonApiModelConfig(options: ModelOptions)
export class Post extends JsonApiModel { }options:
typebaseUrl- if not specified, the globalbaseUrlwill be usedapiVersion- if not specified, the globalapiVersionwill be usedmodelEndpointUrl- if not specified,typewill be used insteadmeta- optional, metadata model
-
Attribute(options: AttributeDecoratorOptions)-
AttributeDecoratorOptions:converter, optional, must implementPropertyConverterinterfaceserializedName, optional
-
By default, the library adds these headers, according to the JSON API MIME Types:
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
You can also add your custom headers to be appended to each http call:
this.datastore.headers = new HttpHeaders({'Authorization': 'Bearer ' + accessToken});Or you can pass the headers as the last argument of any datastore call method:
this.datastore.findAll(Post, {
include: 'comments'
}, new HttpHeaders({'Authorization': 'Bearer ' + accessToken}));and in the save() method:
post.save({}, new HttpHeaders({'Authorization': 'Bearer ' + accessToken})).subscribe();You can add your custom request options to be appended to each http call:
this.datastore.requestOptions = {
withCredentials: false,
myOption: 123
}Error handling is done in the subscribe method of the returned Observables.
If your server returns valid JSON API Error Objects you can access them in your onError method:
import {ErrorResponse} from "ngx-esy-jsonapi";
...
this.datastore.findAll(Post).subscribe(
(posts: Post[]) => console.log(posts),
(errorResponse) => {
if (errorResponse instanceof ErrorResponse) {
// do something with errorResponse
console.log(errorResponse.errors);
}
}
);It's also possible to handle errors for all requests by overriding handleError(error: any): Observable in the datastore.
The library will automatically transform date values into Date objects, and it will serialize them when sending to the server. To do that, remember to set the type of the corresponding attribute as Date:
@JsonApiModelConfig({
type: 'posts'
})
export class Post extends JsonApiModel {
// ...
@Attribute()
created_at: Date;
}Moreover, it should be noted that the following assumptions have been made:
- Dates are expected to be received in one of the ISO 8601 formats, as per the JSON API spec recommendation;
- Dates are always sent in full ISO 8601 format, with local timezone and without milliseconds (example:
2001-02-03T14:05:06+07:00).
Use a Node.js version matching package.json (Node.js 24.15+ on the 24.x line is recommended for this workspace).
npm ci
npm run build # build the library package
npm run lint # lint the library and example
npm run test:ci # library tests with coverage
npm run test:demo # example integration tests; build the library first
npm run build:demo # build the library and production example
npm start # build the library and serve the example locallyTests run with Vitest and jsdom. Coverage reports are written to coverage/ngx-esy-jsonapi.
GitHub Actions runs lint, both builds, library tests, example integration tests, and a package contents check on pushes and pull requests. The separate Pages workflow publishes the tested example when manually triggered on main.
Maintained by Noah (zFl4wless), continuing the work of the upstream authors and contributors.
- The current major targets Angular 22. Angular 20 and 21 releases remain available for compatibility; CI in this branch tests Angular 22.
- Security updates target the current major. See the security policy for supported versions and private reporting.
- For bugs and migration problems, open an issue with your Angular/library versions, reproduction steps, and expected behavior.
- Documentation improvements, minimal reproductions, and fixes with regression coverage are welcome. Include the relevant local checks with your pull request.
- Browse the releases and changelog for version history.
If this library is useful to you, consider starring the repository to help others discover it.
- Gem for generating the model definitions based on active model serializers: https://github.com/oncore-education/jsonapi_models
This library is inspired by the draft of this never implemented library.
MIT, with attribution to Daniele Ghidoli, KarwanK, Noah (zFl4wless), and contributors. The license is included in the published package.