Skip to content
Open
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
42 changes: 38 additions & 4 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -610,9 +610,40 @@
"styleext": "scss"
}
}
},
"syndesi": {
"root": "libs/syndesi",
"sourceRoot": "libs/syndesi/src",
"projectType": "library",
"prefix": "sp",
"architect": {
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"libs/syndesi/tsconfig.lib.json",
"libs/syndesi/tsconfig.spec.json"
],
"exclude": ["**/node_modules/**"]
}
},
"test": {
"builder": "@nrwl/builders:jest",
"options": {
"jestConfig": "libs/syndesi/jest.config.js",
"tsConfig": "libs/syndesi/tsconfig.spec.json",
"setupFile": "libs/syndesi/src/test-setup.ts"
}
}
},
"schematics": {
"@nrwl/schematics:component": {
"styleext": "scss"
}
}
}
},
"defaultProject": "domain",
"defaultProject": "sparkles",
"cli": {
"warnings": {
"typescriptMismatch": false
Expand All @@ -621,13 +652,16 @@
"packageManager": "yarn"
},
"schematics": {
"@nrwl/schematics:application": {
"unitTestRunner": "jest",
"e2eTestRunner": "cypress"
},
"@nrwl/schematics:library": {
"unitTestRunner": "jest",
"framework": "angular"
},
"@nrwl/schematics:application": {
"unitTestRunner": "jest",
"e2eTestRunner": "cypress"
"@nrwl/schematics:component": {
"styleext": "scss"
},
"@nrwl/schematics:node-application": {
"framework": "express"
Expand Down
5 changes: 5 additions & 0 deletions docs/GREEK.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- sýndesi / σύνδεση
- https://en.wiktionary.org/wiki/%CF%83%CF%8D%CE%BD%CE%B4%CE%B5%CF%83%CE%B7
- epafí / επαφή
- https://en.wiktionary.org/wiki/%CE%B5%CF%80%CE%B1%CF%86%CE%AE

1 change: 1 addition & 0 deletions libs/shared/src/lib/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { unique } from './functional';
export class Debug {

public environment: any = {};

private enabled: string[] = [];

public get isDevelop(): boolean {
Expand Down
9 changes: 9 additions & 0 deletions libs/syndesi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Syndesi

> A connected-media format.

Syndesi is inspired by HAL, Siren, and so on.

- http://stateless.co/hal_specification.html
- https://sookocheff.com/post/api/on-choosing-a-hypermedia-format/
- https://tools.ietf.org/html/draft-kelly-json-hal-08
5 changes: 5 additions & 0 deletions libs/syndesi/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
name: 'syndesi',
preset: '../../jest.config.js',
coverageDirectory: '../../coverage/libs/syndesi'
};
8 changes: 8 additions & 0 deletions libs/syndesi/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export * from './lib/api-client.service';
export * from './lib/call';
export * from './lib/embedded.functions';
export * from './lib/link.functions';
export * from './lib/resource.interfaces';
export * from './lib/resource.functions';
export * from './lib/uri';
export * from './lib/syndesi.module';
51 changes: 51 additions & 0 deletions libs/syndesi/src/lib/api-client.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { async, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiClient } from './api-client.service';
import { Resource, ResourceCollection } from './resource.interfaces';

describe('ApiClient', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ ApiClient ]
}).compileComponents();
}));

it('should create', () => {
const service = TestBed.get(ApiClient);
expect(service).toBeTruthy();
const backend = TestBed.get(HttpTestingController);
expect(backend).toBeTruthy();
});

describe(`call()`, () => {
interface Foo {
what: string;
}

const foo: Resource<Foo> = {
_links: {
self: { href: '/foo' }
},
what: 'foo!'
};

interface FooCollectionResource extends ResourceCollection<Foo, any> {}

it(`should return an Observable`, () => {
const api: ApiClient = TestBed.get(ApiClient);
const obs = api.call(foo);
expect(obs).toBeTruthy();
});

xit(`should...`, () => {
const api: ApiClient = TestBed.get(ApiClient);

api.call(foo).get('next').send<FooCollectionResource>().subscribe(next => {
const bar = next.resource;

expect(bar).toBeTruthy();
});
});
});
});
41 changes: 41 additions & 0 deletions libs/syndesi/src/lib/api-client.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Call } from './call';
import { Resource } from './resource.interfaces';

/**
* Inject `ApiClient` to start brosing a nicely crafted connected-media API.
*
* @experimental
*/
@Injectable({ providedIn: 'root' })
export class ApiClient {

constructor(
private http: HttpClient
) {}

/**
* Get the index page of the API at given `url`
*
* @param url URL of index resource, e.g. `/foo/bar/api.json`
* @return Emits a `Call` object for subsequent API calls
*/
public index <T> (url: string): Observable<Call<T>> {
return this.http.get<Resource<T>> (url).pipe(
map(res => new Call(this.http, res)));
}

/**
* Get a subsequent call from a resource obtained prior.
*
* @param resource
* @return A `Call` object for subsequent API calls
*/
public call <T> (resource: Resource<T>): Call<T> {
return new Call(this.http, resource);
}

}
171 changes: 171 additions & 0 deletions libs/syndesi/src/lib/call.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Resource, ResourceMetadata } from './resource.interfaces';
import { expand, UriParams } from './uri';

const toNextCall = <S, T>(call: Call<S>) => {

return function (res: Resource<T> | HttpResponse<Resource<T>>) {
const json = res instanceof HttpResponse ? res.body : res;
const response = res instanceof HttpResponse ? res : undefined;

return new Call<T>(call['_http'], json, response);
};
};

/**
* A `Call` is a single HTTP interaction for exchanging a resource between client and server.
*
* ### How To Use
*
* Inject `ApiClient` and obtain a call instance from a `Resource` obtained prior to this call:
*
* ```ts
* interface Entity {
* whatsUp: string;
* }
*
* @Injectable()
* export class EntityService {
* constructor(private api: ApiClient)
*
* fetchNextPage(res: Respurce<Entity>) {
* return this.api.call(res).get('next').send<>();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a weak link in the Call api. From <R>send(), you always get a Call<R> with a Resource<R>. What about Call<R, D> to get a R extends Resource<D>?

I think we need:

  • call() w/o generics to get an any-typed Resource<any>
  • <R>call() w/ generic type to get an R extends Resource<?>

Thus, the Call<R extends Resource<?>> call class would work with Resource....

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

export class Call2<R> {

  constructor(
    public resource: R & ResourceMetadata
  ) {}

  // PROBLEM: only one of the method declaration overrides seems to work...
  //public next(): Call2<ResourceMetadata>;
  public next<NextResource>(): Call2<NextResource> {
    return new Call2(this.resource);
  }

}

interface FooRes extends Resource {
  bar: string;  
}

const resource1: Resource = {};
const call2 = new Call2({}); // <-- good, compile error

call2.resource._links; // <-- good, type ResourceMetadata found

const next1 = call2.next();
const next2 = call2.next<FooRes>();

next1.resource._links.self; // <-- bad, type ResourceMetadata not recognized
next2.resource._links.self; // <-- good
next2.resource.bar; // <-- good

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In typescript playground, it's supposed to work in TypeScript 3.3

* }
* }
* ```
*
* @param T Type declaration for a `Resource` obtained prior.
* @experimental
*/
export class Call<T> {
private _http: HttpClient;
private _uri: string;
private _method: string;
private _options = {};

// TODO: public resource: T & ResourceMetadata
constructor(
http: HttpClient | Call<any>,
public resource: Resource<T>,
public response?: HttpResponse<T>
) {
if (http instanceof HttpClient) {
this._http = http;
} else {
this._http = http._http;
}
}

public delete(rel: string, params?: UriParams, body?: any): Call<T> {
this.uri(rel, params);
this.method('delete');

return this;
}

public get(rel: string, params?: UriParams): Call<T> {
this.uri(rel, params);
this.method('get');

return this;
}

public head(rel: string, params?: UriParams): Call<T> {
this.uri(rel, params);
this.method('head');

return this;
}

public options(rel: string, params?: UriParams): Call<T> {
this.uri(rel, params);
this.method('options');

return this;
}

public patch(rel: string, params?: UriParams): Call<T> {
this.uri(rel, params);
this.method('patch');

return this;
}

public post(rel: string, params?: UriParams, body?: any): Call<T> {
this.uri(rel, params);
this.method('post');
this.body(body);

return this;
}

public put(rel: string, params?: UriParams, body?: any): Call<T> {
this.uri(rel, params);
this.method('put');
this.body(body);

return this;
}

public uri(rel: string, params?: UriParams): Call<T> {
this._uri = this.expandLink(rel, params);

return this;
}

public method(verb: string): Call<T> {
this._method = verb;

return this;
}

public opts(opts: any): Call<T> {
this._options = opts;

return this;
}

public body(body: any): Call<T> {
this._options = {
...this._options,
body
};

return this;
}

public send<R>(): Observable<Call<R>> {
if (!this._method) {
throw new Error('method is a required parameter! Please set it with method() or one of the short-hands like get().');
}
if (!this._uri) {
throw new Error('uri is a required parameter! Please set it with uri() or one of the short-hands like get().');
}

return this._http.request<Resource<R>>(
this._method,
this._uri,
{
...this._options,
observe: 'response',
responseType: 'json'
}
).pipe(map(toNextCall(this)));
}

private expandLink(rel: string, params?: UriParams): string {
const link = this.resource._links[rel];

if (!link) {
throw new Error(`Link with rel=${rel} does not exist`);
}

if (link instanceof Array) {
throw new Error('Traversing arrays not implemented');
} else {
return expand(link, params);
}
}
}
Loading