1.1.7 • Published 9 months ago

crud-collection v1.1.7

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

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

TypeRequired ParamsDescription
reload()methodsend GET request and return response. Ex: /users
search()methodsend GET request and cancel previous request. Ex: /users
createItem()methodsend POST request with data for save. Ex: /users/1
updateItem()methodsend PUT request with data for update. Ex: /users/1
deleteItem()methodsend DELETE request. Ex: /users/1
selectAll()methodput all loaded items to collection.selectedItems property.
unSelectAll()methodclear collection.selectedItems property.
selectItem()methodselect item from collection.items and put to collection.selectedItems property.
setParams()methodset query param by key
getParams()methodget query params by key
clearParams()methodclear query params by key
getRouteParams()methodget routeParams by key
setRouteParams()methodset routeParams by key
clearRouteParams()methodclear routeParams by key
clear()methodclear 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

TypeRequiredDescription
load()methodsend GET request and put response to item.data
createItem()methodsend POST request
updateItem()methodsend PUT request
deleteItem()methodsend DELETE request
setParams()methodset (key, value) to item.params
getParams()methodget value by key from item.params
clearParams()methodclear all query parmas from item.params
getRouteParams()methodget route params by key
setRouteParams()methodset route params by key
clearRouteParams()methodclear route params by key
clear()methodclear 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

TypeRequiredDescription
createEntity({ name: 'users'})methodcreate crud api for path /users
createGetEntity({ name: 'users'})methodcreate get request for path /users
createPostEntity({ name: 'users'})methodcreate post request for path /users
createUpdateEntity({ name: 'users'})methodcreate put request for path /users
createDeleteEntity({ name: 'users'})methodcreate delete request for path /users
createDeleteManyEntity({ name: 'users'})methodcreate 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

  1. 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 {
}
  1. 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!

1.1.1

9 months ago

1.1.0

9 months ago

1.1.7

9 months ago

1.1.6

9 months ago

1.1.5

9 months ago

1.1.4

9 months ago

1.1.3

9 months ago

1.1.2

9 months ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago