Created
November 1, 2018 16:35
-
-
Save icanhasjonas/34d1d255ba8e5086e13dc5afbabb37a4 to your computer and use it in GitHub Desktop.
Example of decorated interfaces...
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
interface Query { | |
query(sql: string): Promise<any> | |
} | |
class QueryImplementation implements Query { | |
query(sql: string) { | |
return new Promise<string>(resolve => { | |
setTimeout(() => resolve('Hello'), 2000) | |
}) | |
} | |
} | |
class QueryCachedDecorator implements Query { | |
constructor(private readonly inner: Query) {} | |
private cache: { [query: string]: any } = {} | |
async query(sql: string): Promise<any> { | |
let result = this.cache[sql] | |
if (result === undefined) { | |
result = this.cache[sql] = await this.inner.query(sql) | |
} | |
return result | |
} | |
} | |
class QueryDiagonsticsDecoractor implements Query { | |
constructor(private readonly inner: Query, private readonly label: string) {} | |
async query(sql: string): Promise<any> { | |
const label = `${this.label}: ${sql}` | |
console.time(label) | |
try { | |
return await this.inner.query(sql) | |
} finally { | |
console.timeEnd(label) | |
} | |
} | |
} | |
const q: Query = new QueryDiagonsticsDecoractor( | |
new QueryCachedDecorator(new QueryImplementation()), | |
'outer diagnostics' | |
) | |
async function run() { | |
q.query('select * from hello') | |
q.query('select * from hello') | |
q.query('select * from hello') | |
} | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment