From ac85779f3b67ffc2953c17d0824be62b1f0acc86 Mon Sep 17 00:00:00 2001 From: Tim Schiewe Date: Mon, 30 Apr 2018 19:18:46 +0200 Subject: Implement interface/config based infrastructure Fixes #2 --- src/sources/FileSource.ts | 27 +++++++++++++++++++++++++++ src/sources/HttpSource.ts | 22 ++++++++++++++++++++++ src/sources/ISource.ts | 3 +++ 3 files changed, 52 insertions(+) create mode 100644 src/sources/FileSource.ts create mode 100644 src/sources/HttpSource.ts create mode 100644 src/sources/ISource.ts (limited to 'src/sources') diff --git a/src/sources/FileSource.ts b/src/sources/FileSource.ts new file mode 100644 index 0000000..fd4f6f7 --- /dev/null +++ b/src/sources/FileSource.ts @@ -0,0 +1,27 @@ +import {readFile} from 'fs'; + +import {ISource} from './ISource'; + +export class FileSource implements ISource { + private _path: string; + private _data: string = null; + + constructor(path: string) { + this._path = path; + } + + getData(): Promise { + if (this._data) { + return Promise.resolve(this._data); + } + + return new Promise((resolve, reject) => { + readFile(this._path, (err, data) => { + if (err) return reject(err); + + this._data = data.toString(); + resolve(this._data); + }); + }); + } +} diff --git a/src/sources/HttpSource.ts b/src/sources/HttpSource.ts new file mode 100644 index 0000000..45ddd7a --- /dev/null +++ b/src/sources/HttpSource.ts @@ -0,0 +1,22 @@ +import {get} from 'http'; + +import {ISource} from './ISource'; + +export class HttpSource implements ISource { + private _uri: string; + + constructor(path: string) { + this._uri = path; + } + + getData(): Promise { + return new Promise((resolve, reject) => { + get(this._uri, (res) => { + let data = ''; + res.on('error', reject); + res.on('data', chunk => data += chunk); + res.on('end', () => resolve(data)); + }); + }); + } +} diff --git a/src/sources/ISource.ts b/src/sources/ISource.ts new file mode 100644 index 0000000..042aaae --- /dev/null +++ b/src/sources/ISource.ts @@ -0,0 +1,3 @@ +export interface ISource { + getData(): Promise; +} -- cgit v1.3.1