Skip to content

Instantly share code, notes, and snippets.

@davismj
Last active March 23, 2019 19:56
Show Gist options
  • Save davismj/098407af826ebb12309efca660f8a4eb to your computer and use it in GitHub Desktop.
Save davismj/098407af826ebb12309efca660f8a4eb to your computer and use it in GitHub Desktop.
service example
import { JsonService } from './jsonService';
export class ConfigService extends JsonService {
constructor() {
super('path/to/config.json');
}
}
function xhr(method: 'GET' | 'POST', url: string): Promise<object> {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open(method, url, true);
request.addEventListener('readystatechange', () => {
if (request.status >= 200 && request.status < 400) {
resolve(JSON.parse(request.responseText));
} else {
reject(request.responseText);
}
});
request.send();
});
}
// A service class is a "single source of truth." It's just a class that worries about one concern, and provides
// some data or service to the entire application. For example, rather than loading the json in each page that
// needs the json, we load it once in the service class and provide the service class to each page. Of course,
// we could just register the json with an alias on the DI container. That's a form of a service too, because
// it would be the single source of truth. Using a class, like this, is a bit more general, and allows us to do
// things like provide an async API on top of the json, which prevents race conditions.
export class JsonService {
private data: Promise<object>;
constructor(path: string) {
this.data = xhr('GET', path);
}
async get(key: string): Promise<string> {
const data = await this.data;
return data[key];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment