Skip to content

feat(Http): can optionally fetch local resources from app bundle with Http #286

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 23, 2016
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ng-sample/app/global.d.ts
ng-sample/platforms
ng-sample/lib
ng-sample/node_modules
ng-sample/app/nativescript-angular

startup-test/platforms
startup-test/lib
Expand Down
23 changes: 19 additions & 4 deletions nativescript-angular/application.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'globals';
import "zone.js/dist/zone-node"
import "zone.js/dist/zone-node";

import 'reflect-metadata';
import './polyfills/array';
Expand All @@ -14,7 +14,10 @@ import {RootRenderer, Renderer} from '@angular/core/src/render/api';
import {NativeScriptRootRenderer, NativeScriptRenderer} from './renderer';
import {NativeScriptDomAdapter, NativeScriptElementSchemaRegistry, NativeScriptSanitizationService} from './dom-adapter';
import {ElementSchemaRegistry, XHR, COMPILER_PROVIDERS, CompilerConfig} from '@angular/compiler';
import {FileSystemXHR} from './xhr';
import {Http, XHRBackend, BrowserXhr, RequestOptions, ResponseOptions, XSRFStrategy} from '@angular/http';
import {FileSystemXHR} from './http/xhr';
import {NSXSRFStrategy, NSHttp} from './http/ns-http';
import {NSFileSystem} from './file-system/ns-file-system';
import {Parse5DomAdapter} from '@angular/platform-server/src/parse5_adapter';
import {ExceptionHandler} from '@angular/core/src/facade/exception_handler';
import {APPLICATION_COMMON_PROVIDERS} from '@angular/core/src/application_common_providers';
Expand Down Expand Up @@ -87,15 +90,27 @@ export function bootstrap(appComponentType: any,
provide(ElementSchemaRegistry, { useClass: NativeScriptElementSchemaRegistry }),
NS_COMPILER_PROVIDERS,
provide(ElementSchemaRegistry, { useClass: NativeScriptElementSchemaRegistry }),
provide(XHR, { useClass: FileSystemXHR }),
provide(XHR, { useClass: FileSystemXHR })
]

var appProviders = [defaultAppProviders];
if (isPresent(customProviders)) {
appProviders.push(customProviders);
}

var platform = getPlatform();
// Http Setup
// Since HTTP_PROVIDERS can be added with customProviders above, this must come after
appProviders.push([
provide(XSRFStrategy, { useValue: new NSXSRFStrategy()}),
NSFileSystem,
provide(Http, {
useFactory: (backend, options, nsFileSystem) => {
return new NSHttp(backend, options, nsFileSystem);
}, deps: [XHRBackend, RequestOptions, NSFileSystem]
})
]);

var platform = getPlatform();
if (!isPresent(platform)) {
platform = createPlatform(ReflectiveInjector.resolveAndCreate(platformProviders));
}
Expand Down
12 changes: 12 additions & 0 deletions nativescript-angular/file-system/ns-file-system.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {Injectable} from '@angular/core';
import {knownFolders, Folder} from 'file-system';

// Allows greater flexibility with `file-system` and Angular
// Also provides a way for `file-system` to be mocked for testing

@Injectable()
export class NSFileSystem {
public currentApp(): Folder {
return knownFolders.currentApp();
}
}
56 changes: 56 additions & 0 deletions nativescript-angular/http/ns-http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {Injectable} from '@angular/core';
import {Http, XHRConnection, ConnectionBackend, RequestOptions, RequestOptionsArgs, ResponseOptions, ResponseType, Response, Request, BrowserXhr} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import {NSFileSystem} from '../file-system/ns-file-system';

export class NSXSRFStrategy {
public configureRequest(req: any) {
// noop
}
}

@Injectable()
export class NSHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private nsFileSystem: NSFileSystem) {
super(backend, defaultOptions);
}

/**
* Performs a request with `get` http method.
* Uses a local file if `~/` resource is requested.
*/
get(url: string, options?: RequestOptionsArgs): Observable<Response | any> {
if (url.indexOf('~') === 0 || url.indexOf('/') === 0) {
// normalize url
url = url.replace('~', '').replace('/', '');
// request from local app resources
return Observable.fromPromise(new Promise((resolve, reject) => {
let app = this.nsFileSystem.currentApp();
let localFile = app.getFile(url);
if (localFile) {
localFile.readText().then((data) => {
resolve(responseOptions(data, 200, url));
}, (err: Object) => {
reject(responseOptions(err, 400, url));
});
} else {
reject(responseOptions('Not Found', 404, url));
}
}));
} else {
return super.get(url, options);
}
}
}

function responseOptions(body: string | Object, status: number, url: string): Response {
return new Response(new ResponseOptions({
body: body,
status: status,
statusText: 'OK',
type: status === 200 ? ResponseType.Default : ResponseType.Error,
url: url
}));
}

File renamed without changes.
3 changes: 2 additions & 1 deletion nativescript-angular/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@angular/common": "2.0.0-rc.3",
"@angular/compiler": "2.0.0-rc.3",
"@angular/core": "2.0.0-rc.3",
"@angular/http": "2.0.0-rc.3",
"@angular/platform-browser": "2.0.0-rc.3",
"@angular/platform-browser-dynamic": "2.0.0-rc.3",
"@angular/platform-server": "2.0.0-rc.3",
Expand All @@ -39,4 +40,4 @@
"typescript": "^1.8.10"
},
"nativescript": {}
}
}
5 changes: 4 additions & 1 deletion ng-sample/app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { nativeScriptBootstrap } from "nativescript-angular/application";
import { NS_ROUTER_PROVIDERS as NS_ROUTER_PROVIDERS_DEPRECATED } from "nativescript-angular/router-deprecated";
import { NS_ROUTER_PROVIDERS } from "nativescript-angular/router";
import { HTTP_PROVIDERS } from "@angular/http";
import { rendererTraceCategory, routerTraceCategory, listViewTraceCategory } from "nativescript-angular/trace";

import trace = require("trace");
Expand All @@ -23,6 +24,7 @@ import {Benchmark} from './performance/benchmark';
import {ListTest} from './examples/list/list-test';
import {ListTestAsync, ListTestFilterAsync} from "./examples/list/list-test-async";
import {ImageTest} from "./examples/image/image-test";
import {HttpTest} from "./examples/http/http-test";
import {ActionBarTest} from "./examples/action-bar/action-bar-test";
import {ModalTest} from "./examples/modal/modal-test";
import {PlatfromDirectivesTest} from "./examples/platform-directives/platform-directives-test";
Expand All @@ -43,6 +45,7 @@ import { PageRouterOutletNestedAppComponent, PageRouterOutletNestedRouterProvide
// nativeScriptBootstrap(ListTest);
// nativeScriptBootstrap(ListTestAsync);
//nativeScriptBootstrap(ImageTest);
nativeScriptBootstrap(HttpTest, [HTTP_PROVIDERS]);
//nativeScriptBootstrap(ActionBarTest, [NS_ROUTER_PROVIDERS_DEPRECATED], { startPageActionBarHidden: false });
//nativeScriptBootstrap(ActionBarTest, [NS_ROUTER_PROVIDERS_DEPRECATED]);
//nativeScriptBootstrap(ModalTest);
Expand All @@ -51,7 +54,7 @@ import { PageRouterOutletNestedAppComponent, PageRouterOutletNestedRouterProvide
// new router
// nativeScriptBootstrap(RouterOutletAppComponent, [RouterOutletRouterProviders]);
// nativeScriptBootstrap(PageRouterOutletAppComponent, [PageRouterOutletRouterProviders]);
nativeScriptBootstrap(PageRouterOutletNestedAppComponent, [PageRouterOutletNestedRouterProviders]);
// nativeScriptBootstrap(PageRouterOutletNestedAppComponent, [PageRouterOutletNestedRouterProviders]);

// router-deprecated
// nativeScriptBootstrap(NavigationTest, [NS_ROUTER_PROVIDERS_DEPRECATED]);
Expand Down
8 changes: 8 additions & 0 deletions ng-sample/app/examples/http/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"results": [
{
"title": "Test",
"description": "Testing Http local and remote."
}
]
}
50 changes: 50 additions & 0 deletions ng-sample/app/examples/http/http-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {Component} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

/* IMPORTANT
In order to test out the full image example, to fix the App Transport Security error in iOS 9, you will need to follow this after adding the iOS platform:

https://blog.nraboy.com/2015/12/fix-ios-9-app-transport-security-issues-in-nativescript/
*/

@Component({
selector: 'http-test',
template: `
<StackLayout horizontalAlignment="center">
<Button text="Load Local File with Http" (tap)='loadLocal()' cssClass="btn-primary"></Button>
<Button text="Load Remote File with Http" (tap)='loadRemote()' cssClass="btn-primary"></Button>
<Label [text]="title" textWrap="true"></Label>
<Label [text]="description" textWrap="true"></Label>
</StackLayout>
`,
styles: [
`Button {
margin-bottom:20;
}`
]
})
export class HttpTest {
public title: string;
public description: string;

constructor(private http: Http) {

}

public loadLocal() {
this.http.get('~/examples/http/data.json').map(res => res.json()).subscribe((response: any) => {
let user = response.results[0];
this.title = user.title;
this.description = user.description;
});
}

public loadRemote() {
this.http.get(`https://randomuser.me/api/?results=1&nat=us`).map(res => res.json()).subscribe((response: any) => {
let user = response.results[0];
this.title = user.name.first;
this.description = user.email;
});
}
}
1 change: 1 addition & 0 deletions ng-sample/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@angular/common": "2.0.0-rc.3",
"@angular/compiler": "2.0.0-rc.3",
"@angular/core": "2.0.0-rc.3",
"@angular/http": "2.0.0-rc.3",
"@angular/platform-browser": "2.0.0-rc.3",
"@angular/platform-browser-dynamic": "2.0.0-rc.3",
"@angular/platform-server": "2.0.0-rc.3",
Expand Down
62 changes: 62 additions & 0 deletions tests/app/tests/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//make sure you import mocha-config before @angular/core
import {assert} from "./test-config";
import {
async,
inject,
beforeEach,
beforeEachProviders
} from '@angular/core/testing';
import {provide, ReflectiveInjector} from '@angular/core';
import {BaseRequestOptions, ConnectionBackend, Http, HTTP_PROVIDERS, Response, ResponseOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import {MockBackend} from '@angular/http/testing';
import {NSHttp} from "nativescript-angular/http/ns-http";
import {NSFileSystem} from "nativescript-angular/file-system/ns-file-system";
import {NSFileSystemMock, FileResponses} from './mocks/ns-file-system.mock';

describe("Http", () => {
let http: Http;
let backend: MockBackend;

beforeEach(() => {
let injector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS,
BaseRequestOptions,
MockBackend,
provide(NSFileSystem, { useClass: NSFileSystemMock }),
provide(Http, {
useFactory: function (backend: ConnectionBackend, defaultOptions: BaseRequestOptions, nsFileSystem: NSFileSystem) {
return new NSHttp(backend, defaultOptions, nsFileSystem);
},
deps: [MockBackend, BaseRequestOptions, NSFileSystem]
})
]);

backend = injector.get(MockBackend);
http = injector.get(Http);
});

it("should work with local files prefixed with '~'", () => {
http.get('~/test.json').map(res => res.json()).subscribe((response: any) => {
assert.strictEqual(3, response.length);
assert.strictEqual('Alex', response[0].name);
});
});

it("should work with local files prefixed with '/'", () => {
http.get('/test.json').map(res => res.json()).subscribe((response: any) => {
assert.strictEqual(3, response.length);
assert.strictEqual('Panayot', response[2].name);
});
});

it("should work with remote files", () => {
let connection: any;
backend.connections.subscribe((c: any) => connection = c);
http.get('http://www.nativescript.org/test.json').map(res => res.json()).subscribe((response: any) => {
assert.strictEqual(3, response.length);
assert.strictEqual('Rosen', response[1].name);
});
connection.mockRespond(new Response(new ResponseOptions({ body: FileResponses.AWESOME_TEAM })));
});
});
35 changes: 35 additions & 0 deletions tests/app/tests/mocks/ns-file-system.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {Injectable} from '@angular/core';
import {ResponseType, Response, ResponseOptions} from '@angular/http';

export class FileResponses {
public static AWESOME_TEAM: string = '[{"name":"Alex"}, {"name":"Rosen"}, {"name":"Panayot"}]';
}

// Folder mock
class Folder {
public getFile(url: string): any {
let data;
switch (url) {
case 'test.json':
data = FileResponses.AWESOME_TEAM;
break;
default:
throw (new Error('Unsupported file for the testing mock - ns-file-system-mock'));
}
return {
readText: () => {
return new Promise((resolve) => {
resolve(data);
});
}
}
}
}

// Filesystem mock
@Injectable()
export class NSFileSystemMock {
public currentApp(): Folder {
return new Folder();
}
}
2 changes: 1 addition & 1 deletion tests/app/tests/xhr-paths.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//make sure you import mocha-config before @angular/core
import {assert} from "./test-config";
import {FileSystemXHR} from "nativescript-angular/xhr";
import {FileSystemXHR} from "nativescript-angular/http/xhr";

describe("XHR name resolution", () => {
it("resolves relative paths from app root", () => {
Expand Down
1 change: 1 addition & 0 deletions tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@angular/common": "2.0.0-rc.3",
"@angular/compiler": "2.0.0-rc.3",
"@angular/core": "2.0.0-rc.3",
"@angular/http": "2.0.0-rc.3",
"@angular/platform-browser": "2.0.0-rc.3",
"@angular/platform-browser-dynamic": "2.0.0-rc.3",
"@angular/platform-server": "2.0.0-rc.3",
Expand Down