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

rs-restangular

v0.0.7

Published

Restful Resources service for Angular 2 apps

Downloads

118

Readme

RS-Restangular

Build Status Coverage Status David Known Vulnerabilities

This project is the follow-up of the Restangular to Angular 2 written with Typescript.

Table of contents

How do I add this to my project?

You can download this by:

  • Using npm and running npm install rs-restangular

Back to top

Dependencies

Restangular depends on Angular2

Back to top

Starter Guide

Quick Configuration (For Lazy Readers)

This is all you need to start using all the basic Restangular features.

import { NgModule } from '@angular/core';
import { Headers } from '@angular/http';
import { AppComponent } from './app.component';
import { RestangularConfig, RestangularModule } from 'rs-restangular';

// Function for settting the default restangular configuration
export function RestangularConfigFactory (restangularConfig: RestangularConfig) {
  restangularConfig.baseUrl = 'http://api.restng2.local/v1';
  restangularConfig.defaultHeaders = new Headers({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});
} 

// AppModule is the main entry point into Angular2 bootstraping process
@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [
    AppComponent,
  ],
  imports: [
    // Importing RestangularModule and making default configs for restanglar
    RestangularModule.forRoot(RestangularConfigFactory),
  ]
})
export class AppModule {
}

// later in code ...

@Component({
  ...
})
export class OtherComponent {
  constructor(private restangular: Restangular) {
  }

  ngOnInit() {
    // GET http://api.test.local/v1/users/2/accounts
    this.restangular.one('users', 2).all('accounts').getList();
  }

}

With dependecies

import { NgModule } from '@angular/core';
import { Headers, Request } from '@angular/http';
import { AppComponent } from './app.component';
import { SessionService } from './auth/session.service';
import { RestangularConfig, RestangularModule, RestangularPath } from 'rs-restangular';

// Function for settting the default restangular configuration
export function RestangularConfigFactory (restangularConfig: RestangularConfig, http: Http, sessionService: SessionService) {
  restangularConfig.baseUrl = 'http://api.restng2.local/v1'; 

  restangularConfig.addRequestInterceptors((req: Request, operation?: string, path?: RestangularPath): Request => {
    req.headers.set('Authorization': `Bearer ${sessionService.token}`);

    return req;
  });
} 

// AppModule is the main entry point into Angular2 bootstraping process
@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [
    AppComponent,
  ],
  imports: [
    SessionService,
    // Importing RestangularModule and making default configs for restanglar
    RestangularModule.forRoot(RestangularConfigFactory, [Http, SessionService]),
  ]
})
export class AppModule {
} 

Back to top

Using Restangular

Creating Main Restangular object

There are 2 ways of creating a main Restangular object. The first one and most common one is by stating the main route of all requests. The second one is by stating the main route of all requests.

// Only stating main route
restangular.all('accounts');

// Only stating main route
restangular.one('accounts', 1234);

Back to top

Let's code!

Now that we have our main Object let's start playing with it.

// First way of creating a Restangular object. Just saying the base URL
var baseAccounts = restangular.all('accounts');

// This will query /accounts and return a Observable.
baseAccounts.getList().subscribe((accounts: Array<any>) => {
  allAccounts = accounts;
});

var newAccount = {
  name: "Gonto's account"
};

// POST /accounts
baseAccounts.post(newAccount);

// Just ONE GET to /accounts/123/buildings/456
restangular.one('accounts', 123).one('buildings', 456).get();

// Just ONE GET to /accounts/123/buildings
restangular.one('accounts', 123).getList('buildings');

Back to top

Configuring Restangular

Properties

Restangular comes with defaults for all of its properties but you can configure them. So, if you don't need to configure something, there's no need to add the configuration. You can set all these configurations in Restangular.config: RestangularConfig service to change the global configuration. Check the section on this later.

Back to top

baseUrl

The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is /api/v1. The default baseUrl is an empty string which resolves to the same url that Angular 2 is running, but you can also set an absolute url like http://api.example.com/api/v1 if you need to set another domain.

restangularConfig.baseUrl = 'http://api.example.com/api/v1'; 

Back to top

addResponseInterceptor

The responseInterceptor is called after we get each response from the server. It's a function that receives this arguments:

| Param | Type | Description | | ----------| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | data | any | The data received got from the server | | operation | string | The operation made. It'll be the HTTP method used except for a GET which returns a list of element which will return getList so that you can distinguish them. | | path | RestangularPath | The model that's being requested. | | response | Response | Full server response including headers |

Some of the use cases of the responseInterceptor are handling wrapped responses and enhancing response elements with more methods among others.

The responseInterceptor must return the restangularized data element.

// set default header "token"
restangularConfig.addResponseInterceptor((res: any, operation?: string, path?: RestangularPath, url?: string, response?: Response) => {
  console.log(res);
  console.log(path.route);
  return res;
});

Back to top

addRequestInterceptor

The requestInterceptor is called before sending any data to the server. It's a function that must return the element to be requested. This function receives the following arguments:

| Param | Type | Description | | ----------| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | req | Request | The element to send to the server. | | operation | string | The operation made. It'll be the HTTP method used except for a GET which returns a list of element which will return getList so that you can distinguish them. | | path | RestangularPath | The model that's being requested. |

// set default header "token"
restangularConfig.addRequestInterceptor((req: Request, operation?: string, path?: RestangularPath) => {
  console.log(req.url);
  console.log(path.route);
  return req;
});

Back to top

defaultHeaders

You can set default Headers to be sent with every request. Send format: {header_name: header_value}

// set default header "token"
restangularConfig.defaultHeaders = new Headers({ token: "x-restangular" });

Back to top

Methods description

Restangular methods

These are the methods that can be called on the Restangular object.

  • one(route, id): This will create a new Restangular object that is just a pointer to one element with the route route and the specified id.
  • all(route): This will create a new Restangular object that is just a pointer to a list of elements for the specified path.

Back to top

URL Building

Sometimes, we have a lot of nested entities (and their IDs), but we just want the last child. In those cases, doing a request for everything to get the last child is overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without making any requests. Let's see how to do this:

@Component({
  ...
})
export class OtherComponent {
  constructor(private restangular: Restangular) {
  }

  ngOnInit() {
    let restangularSpaces = this.restangular.one('accounts',123).one('buildings', 456).all('spaces');

    // This will do ONE get to /accounts/123/buildings/456/spaces
    restangularSpaces.getList()

    // This will do ONE get to /accounts/123/buildings/456/spaces/789
    this.restangular.one('accounts', 123).one('buildings', 456).one('spaces', 789).get()

    // POST /accounts/123/buildings/456/spaces
    this.restangular.one('accounts', 123).one('buildings', 456).all('spaces').post({name: 'New Space'});

    // DELETE /accounts/123/buildings/456
    this.restangular.one('accounts', 123).one('buildings', 456).remove();
  }
}

Back to top

License

This project is licensed under the MIT license. See the LICENSE file for more info.

Back to top s