# ng-orm

> Rest orm for angular ^2

Latest version **0.0.5** (published 2017-03-02) · MIT license · 0 weekly downloads

## Install

```sh
npm install ng-orm
pnpm add ng-orm
yarn add ng-orm
bun add ng-orm
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.5 |
| Published | 2017-03-02 |
| First published | 2017-03-01 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 5 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Maintainers | scottbwyatt |
| Keywords | rest, orm, angular2, angular 2, $resource, resource, ng |

## Links

- npm: https://www.npmjs.com/package/ng-orm
- Repository: https://github.com/CaliStyle/ng-orm
- Homepage: https://github.com/CaliStyle/ng-orm#readme
- Issues: https://github.com/CaliStyle/ng-orm/issues
- npm.io page: https://npm.io/package/ng-orm

## Dependencies (5)

- [diff](https://npm.io/package/diff.md) ^3.2.0
- [faker](https://npm.io/package/faker.md) ^3.1.0
- [ng2-logger](https://npm.io/package/ng2-logger.md) ^0.1.21
- [@types/diff](https://npm.io/package/@types/diff.md) 0.0.31
- [@types/faker](https://npm.io/package/@types/faker.md) ^3.1.32

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [mongoose-typescript](https://npm.io/package/mongoose-typescript.md) — 85 weekly downloads

## Recent versions

- 0.0.5 (latest) — 2017-03-02
- 0.0.4 — 2017-03-02
- 0.0.3 — 2017-03-02
- 0.0.1 — 2017-03-01

## README

# ng-orm

[![NPM version][npm-image]][npm-url]
[![Build status][ci-image]][ci-url]
[![Dependency Status][daviddm-image]][daviddm-url]
[![Code Climate][codeclimate-image]][codeclimate-url]

REST api ORM with **Angular ^2**

Based on the work of [ng2-rest](https://github.com/darekf77/ng2-rest)

Compatible with

 1. [AngularClass/angular2-webpack-starter](https://github.com/AngularClass/angular2-webpack-starter)
 2. [Angular CLI](https://github.com/angular/angular-cli)

## Install
To install package run:
```sh
$ npm install ng-orm --save
```

## Import module

```ts
	import { Resource } from 'ng-orm/ng-orm';

	@NgModule({
	  bootstrap: [AppComponent],
	  imports: [ 
	    Resource
	  ])
  export class AppModule { }
```

```
Specification
| Name | Parameters  | Description
| :---: | --- | ---: |
| **query** | `(optional) UrlParams[] ` |  fetch array of your models, optionally with parameters |
| **get** | `UrlParams[] ` |   get model by parameters  |
| **save** | `model, UrlParams[] ` |   post object model  |
| **update** | `model, UrlParams[]` |   put object model |
| **remove** | `UrlParams[]` |   remove object by params |parameters |

## Resource

Fit you existing API (not only REST) into new fluent objects...
**Resource** it is more advance version of **SimpleResource**
Examples:

**service.ts**

```ts
     @Injectable()
        export class DatabaseService { 
                        // < enum or 'string', single_model, query_model>
            constructor(private rest: Resource<ENDPOINTS,User,User[]>) {
            
	            // map endpoints and urls
                Resource.map(ENDPOINTS.API.toString(),
	                'http://localhost:/api');
				Resource.map(ENDPOINTS.OTHER_API.toString(),
					'http://example.com/api');
				
				// define your models  
				rest.add(ENDPOINTS.API, 'users'); 
                rest.add(ENDPOINTS.API, 'users/:some_param'); 
                rest.add(ENDPOINTS.API, 'users/:some_param/books/:bookid'); 
                
              }
              
              // create your fluent API
              get model() {
                return {
					getAll:  this.rest
		                .api(ENDPOINTS.API, 'users')
		                .query(),
	                getAllSorted:  this.rest
		                .api(ENDPOINTS.API, '/users/inside')
		                .query([{ sorted: true }]),
	                getSuperUser: this.rest
		                .api(ENDPOINTS.API, 'users/super')
		                .get([{id:0}]),
	                saveCurrentUser : this.rest
		                .api(ENDPOINTS.API, 'users')
		                .save(this.user)
				}
              };

		     
		     
			 mock_controller = (request: MockRequest<any> ):MockResponse
			  => { 
				 let user = request.data;
			     user.id = request.params['id'];
			     return { data:user }; 
			 }
			 
			 users = [ { name:"name1":id:1 }, { name:"name2":id:2 }   ]
             get mocked_models() {
                return {
					getAllMocks:  this.rest
	                .api(ENDPOINTS.API,'users')
	                .mock(JSON.stringify(this.users))
	                .query(),
               getFirstMock:  this.rest
	               .api(ENDPOINTS.API, 'users')
	               .mock(require('user.json')), 1000)
	               .get([{ id:0 }]), // timeout 1000ms = 1s
                getDataFromController:  this.rest
	                .api(ENDPOINTS.API, 'users')
	                .mock(require('user.json')), 0, mock_controller)
	                .get([{id:100}])
				}
             };

              user:User;
              
             }
```
**component.ts**		
```ts
...

import { Subscription } from 'rxjs';
import { Resource } from 'ng-orm';

import { DatabaseService } from './service';

@Component({
  ..
})
export class DemoComponent implements OnInit, OnDestroy {

  constructor(public db: DatabaseService, private snackBar: MdSnackBar) {
    Resource.mockingMode.setMocksOnly();
  }

  handlers: Subscription[] = [];
  users = [];

  public ngOnInit() {
	this.handlers.push(this.db.models.users.subscribe(data => {
      this.users = data;
    }));
  }

 
  public ngOnDestroy() {
    this.handlers.forEach(h => h.unsubscribe())
  }

}
	
```

## Simple data mocking


It is one of the best features here. You don't need a backend for your front-end coding. 

Simplest way to mocking data:
```ts
	// user.json
	[{ id: 12, name: 'Dariusz' },
	{ id: 15, name: 'Marcin' }]


	// service.ts
	...
	getUsers = () => this.rest.api( ENDPOINT.API, modelName )
		.mock( require('./user.json') ).
		query()


	// component.ts
	...
	service.getUsers().subscribe( users => {
		console.log( 'users:', users ); 
		// users: [{ id: 12, name: 'Dariusz' }, { id: 15, name: 'Marcin' }]
	}
```
 

## Mock Controller

 Sample MockController function to just return mocked data based on params:
```ts
	// mock-controller.ts
    export function mockController(
	    request: MockRequest<User> ): MockResponse 
    { 
		// request.data ->   { id: 10, name: 'Dariusz'  }
		// request.params -> {  id: 23 }
		// request.body -> undefined -> only with .save(), update() 
		// request.backend - MockAutoBackend<User>
		// request.method 
		
		let user = request.data;
		user.id = request.params.id;
		return { data:user }; // return nothing or undefined to propagate error
    }
	
	
	// service.ts
	import { mockController } from './mock-controller';
	...
	data = (id) => this.rest.api( ENDPOINT.API, modelName )
		.mock( { id: 10, name: 'Dariusz'  }, mockController).
		get([{ id: id }] )) 


	// component.ts
	...
	service.data(23).subscribe( user => {
		console.log( 'user:', user ); // user: { id: 23, name: 'Dariusz'  }
	}
```


## MockAutoBackend

#### generators [$]

If you wanna ***generate, filter, order, sort*** sample data try third options in controller - 
MockAutoBackend.  It is perfect thing for mocking pagination in your MockController.

By building sample json data object with $ prefix property
 now it is possible to generate very nice random data.
 
###### Array

If value of property is an array, the generator will pick one at random:
 
```js
    {
        "$id" : [1,2,3],
        "name": "Dariusz"
    }
```

The output will be: 
```js
    {
        "id": 2,            // or 1 or 3  - it's random thing,
        "name": "Dariusz"   // property without $ stays the same 
    }
```
Of course it is possible to create json with nested $ fields.

###### String

You also can generate values using [Faker mustache string](https://github.com/marak/Faker.js/#fakerfake) as value.


```js
{
    "$fullTitle" : "{{name.lastName}}, {{name.firstName}} {{name.suffix}}"
}
```

Outputs:

```json
{
    "fullTitle": "Marks, Dean Sr."
}
```

### Pagination example

 Sample MockController generating pagination data with MockAutoBackend:
```ts
	// model.json
	{
        $id : [1,2,3],
        name: 'Dariusz'
    }
	
	// mock-controller.ts
	export function mockController( request: MockRequest<T> ):MockResponse 
    { 
	    console.log(request.backend.models); /// generated models
	    let pageNumber = request.params.pageNumber;
	    let pageSize = request.params.pageSize;
	    let data = request.backend.getPagination( pageNumber, pageSize );
		return { data: data, code: 200 }; // code is optional, 200  is default
    }
	
	// example.service.ts
	import { mockController } from './mock-controller';
	
	...	
	numberOfGeneratedPaginartionModels = 400;	
	getPaginartion =  (params) => this.rest.api( ENDPOINT.API, modelName)
		.mock( requre('./model.json'), 
		mockController,
		this.numberOfGeneratedPaginartionModels).query()
	...


	// component.ts
	...
	currentDisplayedModels = []
	pageSize = 10;
	pageChanged = ( n ) => {
		this.service.getPagination({ pageNumber:n, pageSize: this.pageSize  })
			.subscribe(  partOfMockedPaginationModels => {
				currentDisplayedModels = partOfMockedPaginationModels;
			}) 
	}
    
```

### Headers

With ng-orm you can also easily access your response and request headers
```ts
	// you can also use class Resource for that
	console.log(SimpleResource.Headers.request);
	console.log(SimpleResource.Headers.response);
```

[npm-image]: https://img.shields.io/npm/v/ng-orm.svg?style=flat-square
[npm-url]: https://npmjs.org/package/ng-orm
[ci-image]: https://img.shields.io/circleci/project/github/CaliStyle/ng-orm/nmaster.svg
[ci-url]: https://circleci.com/gh/CaliStyle/ng-orm/tree/master
[daviddm-image]: http://img.shields.io/david/calistyle/ng-orm.svg?style=flat-square
[daviddm-url]: https://david-dm.org/calistyle/ng-orm
[codeclimate-image]: https://img.shields.io/codeclimate/github/calistyle/ng-orm.svg?style=flat-square
[codeclimate-url]: https://codeclimate.com/github/calistyle/ng-orm

---
_Source: https://npm.io/package/ng-orm · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
