crud-collection v1.1.7
Collection
Collection is the library to work with crud request and collect list of loaded items.
Collection class contains all methods to work with list of items (load, create, update, delete, deleteMany).
- Item class contains all methods for to with single item (load, create, update, delete).
Installation
npm i crud-collection
API
import { Collection } from 'crud-collection'
Collection Methods
Type | Required Params | Description | |
---|---|---|---|
reload() | method | send GET request and return response. Ex: /users | |
search() | method | send GET request and cancel previous request. Ex: /users | |
createItem() | method | send POST request with data for save. Ex: /users/1 | |
updateItem() | method | send PUT request with data for update. Ex: /users/1 | |
deleteItem() | method | send DELETE request. Ex: /users/1 | |
selectAll() | method | put all loaded items to collection.selectedItems property. | |
unSelectAll() | method | clear collection.selectedItems property. | |
selectItem() | method | select item from collection.items and put to collection.selectedItems property. | |
setParams() | method | set query param by key | |
getParams() | method | get query params by key | |
clearParams() | method | clear query params by key | |
getRouteParams() | method | get routeParams by key | |
setRouteParams() | method | set routeParams by key | |
clearRouteParams() | method | clear routeParams by key | |
clear() | method | clear all Collection properties to initial |
Example of Collection
.
import { CrudService, CollectionModel } from "crud-collection";
constructor(private _crud: CrudService)
{
const usersCollection: CollectionModel = new Item({
api: this._cruod.createEntity({'users'})
});
usersCollection.hardReloadAfter.creating = true;
usersCollection.hardReloadAfter.updating = true;
usersCollection.hardReloadAfter.deleting = true;
// Transform responce item
usersCollection.mapItem = (item) => {
item['canEdit'] = true;
return item;
}
usersCollection
.setParams('name', 'qwert')
usersCollection.reload().subscribe(res => {
// send Get request by route /users/1?name=querty
// put res list of items to usersCollection.items
// for check loading use in template usersCollection.loading$ | async
});
const dataToCreate = {
name: 'aasdf',
age: 29
}
usersCollection.createItem({ data: dataToCreate }).subscribe(() => {
// send POST request /users and automaticaly reload collection,
// because hardReloadAfter.creating = true;
// for check loading in template use (collection.loadingCrud$ | async).creating
});
const dataToUdpate = {
id: 1,
name: 'aasdf123',
age: 29
}
usersCollection.updateItem({ id: dataToUdpate.id, data: dataToUdpate }).subscribe(() => {
// send PUT request /users/1 and automaticaly reload collection,
// because hardReloadAfter.updating = true;
// for check loading in template use (collection.loadingCrud$ | async).updating
});
const dataToDelete = {
id: 1,
name: 'aasdf123',
age: 29
}
usersCollection.deleteItem({ id: dataToDelete.id }).subscribe(() => {
// send DLETE request /users/1 and automaticaly reload collection,
// because hardReloadAfter.deleting = true;
// for check loading in template use (collection.loadingCrud$ | async).deleting
});
}
import { Item } from 'crud-collection'
Item methods
Type | Required | Description | |
---|---|---|---|
load() | method | send GET request and put response to item.data | |
createItem() | method | send POST request | |
updateItem() | method | send PUT request | |
deleteItem() | method | send DELETE request | |
setParams() | method | set (key, value) to item.params | |
getParams() | method | get value by key from item.params | |
clearParams() | method | clear all query parmas from item.params | |
getRouteParams() | method | get route params by key | |
setRouteParams() | method | set route params by key | |
clearRouteParams() | method | clear route params by key | |
clear() | method | clear all properties of item |
Example of Item
.
import { CrudService } from "crud-collection";
constructor(private _crud: CrudService)
{
const userItem = new Item({
api: this._cruod.createEntity({'users'})
});
userItem
.setRouteParams('id', 1)
.setParams('name', 'qwert')
// console.log(userItem.loading, userItem.loaded);
userItem.load().subscribe( res => {
// send Get request by route /users/1?name=querty
// put res to userItem.data
// console.log(userItem.loading, userItem.loaded);
});
}
import { CrudService } from 'crud-collection'
CrudService Methods
Type | Required | Description | |
---|---|---|---|
createEntity({ name: 'users'}) | method | create crud api for path /users | |
createGetEntity({ name: 'users'}) | method | create get request for path /users | |
createPostEntity({ name: 'users'}) | method | create post request for path /users | |
createUpdateEntity({ name: 'users'}) | method | create put request for path /users | |
createDeleteEntity({ name: 'users'}) | method | create delete request for path /users | |
createDeleteManyEntity({ name: 'users'}) | method | create put request for path /users |
Example CrudService
methods.
import { CrudService } from "crud-collection";
constructor(private _crud: CrudService)
{
const getRequest: GetEntityModel = this._crud.createGetEntity({ name: 'clubs' });
getRequest.get({ id: 2, query: { expand: 'country' }}).subscribe( res => {
// see result
// console.log(getRequest.loading$.value);
// use getRequest.loading$ | async in template
});
const postRequest: PostEntityModel = this._crud.createPostEntity({ name: 'clubs/:id/update', keys: ['id'] });
postRequest.save({ id: 2, data: { name: 'Test name' }, params: { id: 1 } }).subscribe( res => {
// see result
// console.log(postRequest.loading$.value);
// use postRequest.loading$ | async in template
});
const updateRequest: UpdateEntityModel = this._crud.createUpdateEntity({ name: 'clubs/:key1', keys: ['key1'] });
updateRequest.update({ id: 1, data: { name: 'Test name' }, params: { key1: 'key21' } }).subscribe( res => {
// see result
// console.log(updateRequest.loading$.value);
// use updateRequest.loading$ | async in template
});
const deleteRequest: DeleteEntityModel = this._crud.createDeleteEntity({ name: 'clubs' });
deleteRequest.delete({ id: 1 }).subscribe( res => {
// see result
// console.log(deleteRequest.loading$.value);
// use deleteRequest.loading$ | async in template
});
const deleteManyRequest: DeleteManyEntityModel = this._crud.createDeleteManyEntity({ name: 'clubs' });
deleteManyRequest.delete({ body: { ids: [1,2,3] } }).subscribe( res => {
// see result
// console.log(deleteManyRequest.loading$.value);
// use deleteManyRequest.loading$ | async in template
});
}
Usage
- Add the
HttpClientModule
in your root module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
import { TokenInterceptor } from "./token.interceptor";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
- Use the
Crud methods
in your component.
import { Component, OnInit } from '@angular/core';
import { environment } from "../environments/environment";
import {
Collection,
CollectionModel,
CrudService,
Item,
GetEntityModel,
PostEntityModel,
UpdateEntityModel,
DeleteEntityModel,
DeleteManyEntityModel
} from "collection";
Collection.prototype.mapResponse = (res) => {
return {
items: res.data,
meta: res.meta.pagination
};
};
Item.prototype.mapResponse = (res) => {
return res.data;
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'angular-collection';
collection: CollectionModel;
ngOnInit() {
this.collection.onLoad$.subscribe( () => {
// listener on collection load data
});
this.reload();
}
reload() {
this.collection.setParams('page', 1);
this.collection.reload().subscribe(( res ) => {
// see response
})
}
nextPage() {
let page = this.collection.getParams('page');
this.collection.setParams('page', +page + 1);
this.collection.search();
}
constructor(
private _crud: CrudService
) {
this._crud.apiUrl = environment.apiUrl;
this.collection = new Collection({
api: this._crud.createEntity({ name: 'users' })
});
}
}
*** Use the Collection
in your component for crud operations.
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AppService } from './app.service';
import {
CollectionModel,
CrudService,
Collection
} from 'crud-collection';
@Component({
selector: 'projects-list',
templateUrl: ['./projects-list.component.html'],
styleUrls: ['./projects-list.component.css']
})
export class ProjectsListComponent implements OnInit {
collection: CollectionModel;
getAll() {
this.collection.reload().subscribe( res => {
// Send GET request into path '/projects' with default query params
// per_page, page, search_query
})
/*
For set query params use collection.setParams(key, value),
this.collection
.setParams('page', 2)
.setParams('search_query', '1234')
.search();
*/
}
create(data) {
this.collection.createItem({ data }).subscribe( res => {
// Send POST request into path '/projects' with data
this.collection.search();
})
}
update(data) {
this.collection.updateItem({ id: data.id, data }).subscribe( res => {
// Send PUT request into path '/projects/:id' with data
this.collection.search();
})
}
delete(id) {
this.collection.deleteItem({ id }).subscribe( res => {
// Send DELETE request into path '/projects/:id'
this.collection.search();
})
}
deleteMany(idsArray) {
this.collection.deleteMany({ ids: idsArray }).subscribe( res => {
// Send DELETE request into path '/projects' with body data ids: [...idsArray]
this.collection.search();
})
}
ngOnInit() {
this.collection.search();
}
constructor(private _crud: CrudService) {
this.collection = new Collection({
api: this._crud.createEntity({ name: 'projects' }),
params: {
page: 1,
per_page: 15,
search_quesry: 'Project Name'
}
});
}
}
// projects-list.component.html
<section class="projects-wrapper">
<ng-container *ngFor="let project of collection.items$ | async">
<div class="project-item">
{{ project?.name }}
</div>
</ng-container>
<ng-container *ngIf="collection.loading$ | async">
<span>...Loading</span>
</ng-container>
</section>
Examples
https://medium.com/@i.perun290195/angular-crud-with-crud-collection-84e3b7769c61
Extra
P.S. Feel free to contact us if you need help.
email: i.perun290195@gmail.com
Thank you!
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago