Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,23 @@ export class AppModule { }

Firstly, create your `Datastore` service:
- Extend the `JsonApiDatastore` class
- Decorate it with `@JsonApiDatastoreConfig`, set the `baseUrl` for your APIs and map your models
- Decorate it with `@JsonApiDatastoreConfig`, set the `baseUrl` for your APIs and map your models (Optional: you can set `apiVersion`, `baseUrl` will be suffixed with it)
- Pass the `Http` depencency to the parent constructor.

```typescript
import { JsonApiDatastoreConfig, JsonApiDatastore } from 'angular2-jsonapi';
import { JsonApiDatastoreConfig, JsonApiDatastore, DatastoreConfig } from 'angular2-jsonapi';

@Injectable()
@JsonApiDatastoreConfig({
const config: DatastoreConfig = {
baseUrl: 'http://localhost:8000/v1/',
models: {
posts: Post,
comments: Comment,
users: User
}
})
}

@Injectable()
@JsonApiDatastoreConfig(config)
export class Datastore extends JsonApiDatastore {

constructor(http: Http) {
Expand Down Expand Up @@ -405,6 +407,45 @@ export class JsonApiMetaModel {
}
```

### Datastore config

Datastore config can be specified through the `JsonApiDatastoreConfig` decorator and/or by setting a `config` variable of the `Datastore` class. If an option is specified in both objects, a value from `config` variable will be taken into account.

```typescript
@JsonApiDatastoreConfig(config: DatastoreConfig)
export class Datastore extends JsonApiDatastore {
private customConfig: DatastoreConfig = {
baseUrl: 'http://something.com'
}

constructor() {
this.config = this.customConfig;
}
}
```

`config`:

* `models` - all the models which will be stored in the datastore
* `baseUrl` - base API URL
* `apiVersion` - optional, a string which will be appended to the baseUrl


### Model config

```typescript
@JsonApiModelConfig(options: ModelOptions)
export class Post extends JsonApiModel { }
```

`options`:

* `type`
* `baseUrl` - if not specified, the global `baseUrl` will be used
* `apiVersion` - if not specified, the global `apiVersion` will be used
* `modelEndpointUrl` - if not specified, `type` will be used instead
* `meta` - optional, metadata model


### Custom Headers

Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export * from './models/json-api.model';
export * from './models/error-response.model';
export * from './models/json-api-query-data';

export * from './interfaces/datastore-config.interface';
export * from './interfaces/model-config.interface';

export * from './providers';

export * from './module';
Expand Down
5 changes: 5 additions & 0 deletions src/interfaces/datastore-config.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface DatastoreConfig {
apiVersion?: string;
baseUrl?: string;
models?: Object;
}
9 changes: 9 additions & 0 deletions src/interfaces/model-config.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {JsonApiMetaModel} from '../models/json-api-meta.model';

export interface ModelConfig {
type: string;
apiVersion?: string;
baseUrl?: string;
modelEndpointUrl?: string;
meta?: JsonApiMetaModel;
}
7 changes: 5 additions & 2 deletions src/models/json-api.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Headers } from '@angular/http';
import find from 'lodash-es/find';
import { Observable } from 'rxjs/Observable';
import { JsonApiDatastore, ModelType } from '../services/json-api-datastore.service';
import { ModelConfig } from '../interfaces/model-config.interface';

export class JsonApiModel {

id: string;
[key: string]: any;

Expand Down Expand Up @@ -61,6 +61,10 @@ export class JsonApiModel {
Reflect.defineMetadata('Attribute', attributesMetadata, this);
}

get modelConfig(): ModelConfig {
return Reflect.getMetadata('JsonApiModelConfig', this.constructor);
}

private parseHasMany(data: any, included: any, level: number): void {
let hasMany: any = Reflect.getMetadata('HasMany', this);
if (hasMany) {
Expand Down Expand Up @@ -144,5 +148,4 @@ export class JsonApiModel {
this._datastore.addToStore(newObject);
return newObject;
}

}
60 changes: 43 additions & 17 deletions src/services/json-api-datastore.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {TestBed} from '@angular/core/testing';
import * as dateParse from 'date-fns/parse';
import {Author} from '../../test/models/author.model';
import {CustomAuthor, AUTHOR_API_VERSION, AUTHOR_MODEL_ENDPOINT_URL} from '../../test/models/custom-author.model';
import {AUTHOR_BIRTH, AUTHOR_ID, AUTHOR_NAME, BOOK_TITLE, getAuthorData} from '../../test/fixtures/author.fixture';
import {
BaseRequestOptions,
Expand All @@ -12,13 +13,16 @@ import {
ResponseOptions
} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {BASE_URL, Datastore} from '../../test/datastore.service';
import {BASE_URL, API_VERSION, Datastore} from '../../test/datastore.service';
import {BASE_URL_FROM_CONFIG, API_VERSION_FROM_CONFIG, DatastoreWithConfig} from '../../test/datastore-with-config.service';
import {ErrorResponse} from '../models/error-response.model';
import {getSampleBook} from '../../test/fixtures/book.fixture';
import {Book} from '../../test/models/book.model';
import { ModelConfig } from '../index';


let datastore: Datastore;
let datastoreWithConfig: Datastore;
let backend: MockBackend;

// workaround, see https://github.com/angular/angular/pull/8961
Expand All @@ -28,9 +32,7 @@ class MockError extends Response implements Error {
}

describe('JsonApiDatastore', () => {

beforeEach(() => {

TestBed.configureTestingModule({
providers: [
{
Expand All @@ -42,30 +44,54 @@ describe('JsonApiDatastore', () => {
},
MockBackend,
BaseRequestOptions,
Datastore
Datastore,
DatastoreWithConfig
]
});

datastore = TestBed.get(Datastore);
datastoreWithConfig = TestBed.get(DatastoreWithConfig);
backend = TestBed.get(MockBackend);

});


describe('query', () => {
it('should build basic url from the data from datastore decorator', () => {
const authorModelConfig: ModelConfig = Reflect.getMetadata('JsonApiModelConfig', Author);

it('should build basic url', () => {
backend.connections.subscribe((c: MockConnection) => {

expect(c.request.url).toEqual(BASE_URL + 'authors');
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/${authorModelConfig.type}`);
expect(c.request.method).toEqual(RequestMethod.Get);
});

datastore.query(Author).subscribe();
});

it('should build basic url and apiVersion from the config variable if exists', () => {
const authorModelConfig: ModelConfig = Reflect.getMetadata('JsonApiModelConfig', Author);

backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(`${BASE_URL_FROM_CONFIG}/${API_VERSION_FROM_CONFIG}/${authorModelConfig.type}`);
expect(c.request.method).toEqual(RequestMethod.Get);
});

datastoreWithConfig.query(Author).subscribe();
});

it('should use apiVersion and modelEnpointUrl from the model instead of datastore if model has apiVersion and/or modelEndpointUrl specified', () => {
const authorModelConfig: ModelConfig = Reflect.getMetadata('JsonApiModelConfig', CustomAuthor);

backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(`${BASE_URL_FROM_CONFIG}/${AUTHOR_API_VERSION}/${AUTHOR_MODEL_ENDPOINT_URL}`);
expect(c.request.method).toEqual(RequestMethod.Get);
});

datastoreWithConfig.query(CustomAuthor).subscribe();
});

it('should set JSON API headers', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(BASE_URL + 'authors');
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/authors`);
expect(c.request.method).toEqual(RequestMethod.Get);
expect(c.request.headers.get('Content-Type')).toEqual('application/vnd.api+json');
expect(c.request.headers.get('Accept')).toEqual('application/vnd.api+json');
Expand All @@ -75,8 +101,8 @@ describe('JsonApiDatastore', () => {

it('should build url with nested params', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).not.toEqual(BASE_URL);
expect(c.request.url).toEqual(BASE_URL + 'authors?' +
expect(c.request.url).not.toEqual(`${BASE_URL}/${API_VERSION}`);
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/` + 'authors?' +
encodeURIComponent('page[size]') + '=10&' +
encodeURIComponent('page[number]') + '=1&' +
encodeURIComponent('include') + '=comments&' +
Expand All @@ -96,7 +122,7 @@ describe('JsonApiDatastore', () => {

it('should have custom headers', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(BASE_URL + 'authors');
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/authors`);
expect(c.request.method).toEqual(RequestMethod.Get);
expect(c.request.headers.has('Authorization')).toBeTruthy();
expect(c.request.headers.get('Authorization')).toBe('Bearer');
Expand All @@ -107,7 +133,7 @@ describe('JsonApiDatastore', () => {

it('should override base headers', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(BASE_URL + 'authors');
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/authors`);
expect(c.request.method).toEqual(RequestMethod.Get);
expect(c.request.headers.has('Authorization')).toBeTruthy();
expect(c.request.headers.get('Authorization')).toBe('Basic');
Expand Down Expand Up @@ -262,8 +288,8 @@ describe('JsonApiDatastore', () => {
describe('saveRecord', () => {
it('should create new author', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).not.toEqual(BASE_URL);
expect(c.request.url).toEqual(BASE_URL + 'authors');
expect(c.request.url).not.toEqual(`${BASE_URL}/${API_VERSION}`);
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/authors`);
expect(c.request.method).toEqual(RequestMethod.Post);
let obj = c.request.json().data;
expect(obj.attributes.name).toEqual(AUTHOR_NAME);
Expand Down Expand Up @@ -339,8 +365,8 @@ describe('JsonApiDatastore', () => {
describe('updateRecord', () => {
it('should update author', () => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).not.toEqual(BASE_URL);
expect(c.request.url).toEqual(BASE_URL + 'authors/1');
expect(c.request.url).not.toEqual(`${BASE_URL}/${API_VERSION}/authors`);
expect(c.request.url).toEqual(`${BASE_URL}/${API_VERSION}/authors/1`);
expect(c.request.method).toEqual(RequestMethod.Patch);
let obj = c.request.json().data;
expect(obj.attributes.name).toEqual(AUTHOR_NAME);
Expand Down
Loading