This repository was archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Basic Issue List Implementation with localStorage caching #49
Open
jeffbcross
wants to merge
1
commit into
angular:master
Choose a base branch
from
jeffbcross:load-issues
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
declare var jasmine:any; | ||
declare var expect:any; | ||
import { | ||
it, | ||
iit, | ||
describe, | ||
ddescribe, | ||
// expect, | ||
inject, | ||
injectAsync, | ||
TestComponentBuilder, | ||
beforeEach, | ||
beforeEachProviders | ||
} from 'angular2/testing'; | ||
import {provide} from 'angular2/core'; | ||
import {AngularFire, FIREBASE_PROVIDERS, defaultFirebase} from 'angularfire2'; | ||
import {Github} from './github'; | ||
import {HTTP_PROVIDERS, XHRBackend, Response, BaseResponseOptions} from 'angular2/http'; | ||
import {MockBackend, MockConnection} from 'angular2/http/testing'; | ||
import {LOCAL_STORAGE} from '../config'; | ||
import {ScalarObservable} from 'rxjs/observable/ScalarObservable'; | ||
|
||
describe('Github Service', () => { | ||
|
||
beforeEachProviders(() => [ | ||
Github, | ||
FIREBASE_PROVIDERS, | ||
defaultFirebase('https://issue-zero.firebaseio.com'), | ||
HTTP_PROVIDERS, | ||
provide(XHRBackend, { | ||
useClass: MockBackend | ||
}), | ||
provide(LOCAL_STORAGE, { | ||
useClass: MockLocalStorage | ||
})]); | ||
|
||
beforeEach(inject([AngularFire], (angularFire) => { | ||
angularFire.auth = new ScalarObservable({github: { | ||
accessToken: 'fooAccessToken' | ||
}}) | ||
})); | ||
|
||
|
||
it('should make a request to the Github API', inject([Github, XHRBackend], (service: Github, backend: MockBackend) => { | ||
var nextSpy = jasmine.createSpy('next') | ||
backend.connections.subscribe(nextSpy); | ||
|
||
var fetchObservable = service.fetch('/repo', 'bar=baz'); | ||
expect(nextSpy).not.toHaveBeenCalled(); | ||
fetchObservable.subscribe(); | ||
expect(nextSpy).toHaveBeenCalled(); | ||
})); | ||
|
||
|
||
it('should not make a request to the Github API if value exists in cache', inject( | ||
[Github, XHRBackend, LOCAL_STORAGE], | ||
(service: Github, backend: MockBackend, localStorage) => { | ||
var connectionCreated = jasmine.createSpy('connectionCreated'); | ||
var valueReceived = jasmine.createSpy('valueReceived'); | ||
backend.connections.subscribe(connectionCreated); | ||
|
||
localStorage.setItem('izCache/repo', '{"issues": ["1"]}'); | ||
|
||
var fetchObservable = service.fetch('/repo', 'bar=baz'); | ||
expect(connectionCreated).not.toHaveBeenCalled(); | ||
fetchObservable.subscribe(valueReceived); | ||
expect(connectionCreated).not.toHaveBeenCalled(); | ||
expect(valueReceived.calls.argsFor(0)[0]).toEqual({issues: ['1']}) | ||
})); | ||
|
||
it('should set http response json to cache', inject( | ||
[Github, XHRBackend, LOCAL_STORAGE], | ||
(service: Github, backend: MockBackend, localStorage) => { | ||
var setItemSpy = spyOn(localStorage, 'setItem'); | ||
backend.connections.subscribe((c:MockConnection) => { | ||
c.mockRespond(new Response(new BaseResponseOptions().merge({body: `{"issues": ["1","2","3"]}`}))); | ||
}); | ||
|
||
var fetchObservable = service.fetch('/repo', 'bar=baz'); | ||
fetchObservable.subscribe(); | ||
expect(setItemSpy).toHaveBeenCalledWith('izCache/repo', '{"issues": ["1","2","3"]}'); | ||
})); | ||
}); | ||
|
||
class MockLocalStorage { | ||
private _cache = {}; | ||
getItem (key:string): string { | ||
return key in this._cache ? this._cache[key] : null; | ||
} | ||
|
||
setItem (key:string, value:string): void { | ||
this._cache[key] = value; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import {AngularFire} from 'angularfire2'; | ||
import {Inject, Injectable} from 'angular2/core'; | ||
import {Http} from 'angular2/http'; | ||
import {Observable} from 'rxjs/Observable'; | ||
import {ScalarObservable} from 'rxjs/observable/ScalarObservable'; | ||
import {ErrorObservable} from 'rxjs/observable/ErrorObservable'; | ||
import {_catch} from 'rxjs/operator/catch'; | ||
import {map} from 'rxjs/operator/map'; | ||
import {_do} from 'rxjs/operator/do'; | ||
import {mergeMap} from 'rxjs/operator/mergeMap'; | ||
|
||
import {User, Repo} from './types'; | ||
import {LOCAL_STORAGE} from '../config'; | ||
|
||
const GITHUB_API = 'https://api.github.com'; | ||
|
||
interface LocalStorage { | ||
getItem(key:string): string; | ||
setItem(key:string, value:string): void; | ||
} | ||
|
||
@Injectable() | ||
export class Github { | ||
|
||
constructor( | ||
private _http:Http, | ||
@Inject(LOCAL_STORAGE) private _localStorage:LocalStorage, | ||
private _af:AngularFire) {} | ||
|
||
fetch(path:string, params?: string): Observable<Repo[]> { | ||
var accessToken = map.call(this._af.auth, (auth:FirebaseAuthData) => auth.github.accessToken); | ||
var httpReq = mergeMap.call(accessToken, (tokenValue) => this._httpRequest(path, tokenValue, params)); | ||
return _catch.call(this._getCache(path), () => httpReq); | ||
} | ||
|
||
_httpRequest (path:string, accessToken:string, params?:string) { | ||
var url = `${GITHUB_API}${path}?${params ? params + '&' : ''}access_token=${accessToken}` | ||
var reqObservable = this._http.get(url); | ||
// Set the http response to cache | ||
// TODO(jeffbcross): issues should be cached in more structured and queryable format | ||
var setCacheSideEffect = _do.call(reqObservable, res => this._setCache(path, res.text())); | ||
// Get the JSON object from the response | ||
return map.call(setCacheSideEffect, res => res.json()); | ||
} | ||
|
||
/** | ||
* TODO(jeffbcross): get rid of this for a more sophisticated, queryable cache | ||
*/ | ||
_getCache (path:string): Observable<Repo> { | ||
var cacheKey = `izCache${path}`; | ||
var cache = this._localStorage.getItem(cacheKey); | ||
if (cache) { | ||
return new ScalarObservable(JSON.parse(cache)); | ||
} else { | ||
return ErrorObservable.create(null); | ||
} | ||
} | ||
|
||
/** | ||
* TODO(jeffbcross): get rid of this for a more sophisticated, queryable cache | ||
*/ | ||
_setCache(path:string, value:string): void { | ||
var cacheKey = `izCache${path}`; | ||
this._localStorage.setItem(cacheKey, value); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
export type Repo = { | ||
full_name: string; | ||
owner: User; | ||
} | ||
|
||
export type User = { | ||
avatar_url: string; | ||
login: string; | ||
} | ||
|
||
export enum GithubObjects { | ||
User, | ||
Repo, | ||
Issue | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import {Component, EventEmitter, Input, Output} from 'angular2/core'; | ||
import {MD_LIST_DIRECTIVES} from '@angular2-material/list'; | ||
|
||
// truncate.ts | ||
import {Pipe} from 'angular2/core' | ||
|
||
@Pipe({ | ||
name: 'truncate' | ||
}) | ||
export class TruncatePipe { | ||
transform(value: string, args: string[]) : string { | ||
let limit = args.length > 0 ? parseInt(args[0], 10) : 10; | ||
let trail = args.length > 1 ? args[1] : '...'; | ||
|
||
return value.length > limit ? value.substring(0, limit) + trail : value; | ||
} | ||
} | ||
|
||
|
||
@Component({ | ||
selector: 'issue-row', | ||
template: ` | ||
<md-list-item> | ||
<img md-list-avatar [src]="issue.user.avatar_url + '&s=40'" alt="{{issue.user.login}} logo"> | ||
<span md-line> {{issue.title}} </span> | ||
<p md-line> | ||
@{{issue.user.login}} -- {{issue.body | truncate: 140 : '...' }} | ||
</p> | ||
<md-list-item> | ||
`, | ||
providers: [], | ||
directives: [MD_LIST_DIRECTIVES], | ||
pipes: [TruncatePipe] | ||
}) | ||
export class IssueRow { | ||
@Input('issue') issue:any; | ||
|
||
constructor() {} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Try this pattern:
function getFromCache(x): Observable
function getFromNetwork(x): Observable
Observable
.concat(
getFromCache(x),
getFromNetwork(x)
.do(v => setCache(x, v)))
.filter(v => v != undefined)
.first()