Skip to content

Instantly share code, notes, and snippets.

@IniZio
Last active July 22, 2019 02:47
Show Gist options
  • Save IniZio/2967f82bd8ef8473b30a697dbcf88366 to your computer and use it in GitHub Desktop.
Save IniZio/2967f82bd8ef8473b30a697dbcf88366 to your computer and use it in GitHub Desktop.
const onReady = Symbol('onReady');
const PRESERVED_METHODS = ["property", "constructor", "__defineGetter__", "__defineSetter__", "hasOwnProperty", "__lookupGetter__", "__lookupSetter__", "isPrototypeOf", "propertyIsEnumerable", "toString", "valueOf", "__proto__", "toLocaleString"]
function getAllMethodNames (obj: any, depth = Infinity) {
const methods = new Set<String>()
while (depth-- && obj) {
for (const key of Reflect.ownKeys(obj)) {
if (typeof key === 'string' && PRESERVED_METHODS.indexOf(key) < 0 && typeof obj[key] === 'function')
methods.add(key)
}
obj = Reflect.getPrototypeOf(obj)
}
return [...methods]
}
function classDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
private _ready: boolean = true;
private _onloads: any[] = [];
[onReady]<T extends (...args: any[]) => any>(callback: T) {
console.log('ready?')
return this._ready ? callback : (e: Parameters<T>) => new Promise((resolve, reject) => {this._onloads.push((e: Parameters<T>) => callback(e).then(resolve).catch(reject))})
}
constructor(...args: any[]) {
super(...args)
getAllMethodNames(this).forEach((key) => {
console.log('key: ', key)
if (typeof this[key as keyof this] === 'function') {
const method = this[key as keyof this]
this[key as keyof this] = this[onReady](method)
}
})
}
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
bello() {
console.log('yho')
}
}
console.log(new Greeter("world").bello());
const service = createService({
async pre () {
await prepareAPIKey()
return api
}
})({
})
@service()
class GoogleSheet {
pre: () => {
new Promise(resolve => {
this._gapi.load('client:auth2', resolve)
}).then(() => {
// blablabla
})
}
read() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment