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

ngx-http-annotations

v0.8.0

Published

This is a library to angular to use http request via decorator/annotations

Downloads

17

Readme

ngx-http-annotations

This library allows to interact with rest api in your angular app. It contains:

  • Annotations for http methods (@GET, @POST, @PUT, @DELETE, @OPTIONS, @HEAD, @PATCH)
  • Annotations for adding headers, setting produces results and intercepting response
  • Params annotations

forked from : https://github.com/Mixalloff/ngx-http-rest

Installation

Install through npm:

$ npm install ngx-http-annotations --save

Development

Example of using library.

  1. Plug the HttpRestModule into your AppModule
import { NgxHttpAnnotationsModule } from 'ngx-http-annotations';
import { NgModule } from '@angular/core';

@NgModule({
  imports: [
    NgxHttpAnnotationsModule
  ]
})
export class AppModule {
}
  1. Create a service to work with rest api. Put annotations on the class, methods and params.
import {  GET, POST, DELETE, Path, PathParam, Body, QueryParam, QueryParams, ResponseObservable } from 'ngx-http-annotations';
import { Injectable } from '@angular/core';
import RestConfig from 'app/core/configs/rest.config';

interface GoodsItem {
  id: number,
  name: string,
  price: number,
  sales?: boolean;
  desc?: string;
  children?: Array<GoodsItem>;
}

@Injectable()
@Headers({
  'someHeader1': 'headerValue1',
  'someHeader2': 'headerValue2'
})
@Path(`/test/goods`)
export class SomeRestService {

  @GET
  getGoods(@QueryParams /* Object with queryParams { [name: string]: [value: any] } */ queryObj?: any): any {}

  @GET
  getGoodsBySomeParam(@QueryParam('sales') /* ...?sales= */ isSold: boolean): any {}

  @GET
  @Path('/:id')
  getGoodsItemById(@PathParam('id') itemId: number): any {}

  @GET
  @Path('/:id/child/:childId') /* Few path params */
  getChildrenOfSomeGoods(@PathParam('id') id: number,
                         @PathParam('childId') childId: number
                         @QueryParam('sales') isSold: boolean,
                         @QueryParam('someParam') some: any): any {}

  @POST
  @Path('/create')
  createGoods(@Body /* Body of POST request */ goodsObject: GoodsItem): any {}

  @DELETE
  @Path('/:id')
  removeGoodsById(@PathParam('id') itemId: number): any {}
  
  @GET
  @Path('posts')
  /**
  * getPostForUserId(3, 2) : call the the url /posts?userId=2 and only take 3 results
  */
  public getPostForUserId(number: number, @QueryParam('userId') userId: number, @ResponseObservable res: Observable<any> = undefined): Observable<any> {
    return res.pipe(map((response) => response.slice(0, number)));
  }


}
  1. Call the request method from component
import { Component, OnInit } from '@angular/core';
import { SomeRestService } from './some-rest.service';

@Component({
  selector: 'some-test-component',
  templateUrl: './test-component.component.html',
  styleUrls: ['./test-component.component.css'],
  providers: [SomeRestService]
})
export class TestComponent implements OnInit {
  constructor(private someRestService: SomeRestService){}

  ngOnInit() {
    this.someRestService
      .getGoods()
      .subscribe( goods => console.log(goods) );
  }
}

Description

Available annotations:

  1. Request methods @GET, @POST, @PUT, @DELETE, @OPTIONS, @HEAD, @PATCH - marks methods implementing the corresponding requests
  2. Added settings
  • @Path - set path of url for request. Combined class @Path annotation value and current method @Path. Path params passed with ":". For example @Path('/someurl/:someParam')
  • @Headers - set headers for request (if annotate class, then all class methods getting this headers. method Headers merge with class Headers)
  • @Produces - setting expected response type. By default Reponse transformed by .json() method
  • @Observes - setting http observes.
  1. Parameters
  • @PathParam (or @Path) - pass current parameter by name to collected url. Example: someFunc(@PathParam('id') itemId: number) {}
  • @Body - pass body object into request. Ex.: someMethod(@Body bodyObject: any){}
  • @QueryParam - pass single query parameters into request. Ex.: someMethod(@QueryParam('a') a: any, @QueryParam('b') b: any) {}. someMethod(1, 2) -> ..requested_url..?a=1&b=2
  • @QueryParams - pass object with few query params. Ex.: someMethod(@QueryParams queryObj: any){}. someMethod({x: 1, y: 2, z: 3}) -> ..requested_url..?x=1&y=2&z=3
  • @ResponseObservable - specify in witch function params, the response observable will be added. Ex.: someMethod(@ResponseObservable res: Observable = undefined){ /* transform request */ return res; }. need to initialise as undefined to pass compile error, and return a response.

Transform response with all rxjs function

By adding the parameters @ResponseObservable you can specify, where add the observable response,

  
  @GET
  @Path('posts')
  /**
  * getPostForUserId(3, 2) : call the the url /posts?userId=2 and only take 3 results
  */
  public getPostForUserId(number: number, @QueryParam('userId') userId: number, @ResponseObservable res: Observable<any> = undefined): Observable<any> {
    return res.pipe(map((response) => response.slice(0, number)));
  }

Mocks calls

To have a feature to enable mocks api. When enabled, will call directly the function rather than call the http request.

To enable Mocks : in a module provider use this :

providers: [{ provide: HTTP_ANNOTATIONS_USE_MOCKS, useValue: true }]

You can specify a boolean value, or have a specific function, that will be used to know if the apps will use mock. This could help you to define mock only for specific call.

providers: [{ provide: HTTP_ANNOTATIONS_USE_MOCKS, useValue: (url, requestType, params, args): boolean => {
       console.log('useMock : ', url, requestType, params, args);
      return requestType === 'Get' ? true : false;
    } }]

define your mocks by return a fake observable, with your mock data.

  @GET
  @Path('posts/:id')
  public getPost(@PathParam('id') id: number): Observable<any> {
    return of([{id: id, title: 'mock true'}]);
  }

Change logs

0.6.x

-> updates to the latest versions of Angular -> Rename library to ngx-http-annotations -> add @ResponseObservable to transform response.

0.6.2 et 0.6.3

-> update to build the library with angular, to avoid error when build in --prod

0.7.x

-> Add a mock feature. -> Update dependency to latest

0.7.3 -> Add delay: Add a beta feature, to add a delay to all requests, or have a function that returns this delay. This could be useful, in the mock feature. By default, all mock, will have a default delay. But could be also added without mock, to simulate long request. -> Use all httpClient methods rather than use request method, use the corresponding method (get, put, delete ...). In order, to avoid issue with request method that throw a first empty error. -> Update dependencies: Update to version 13 of Angular.

0.8.0 -> Updates to Angular 16, and compile libs to ivy -> change to nx workspace -> Add unit tests

Source and issues

Code are located in github : https://github.com/manudss/ngx-http-annotations