ts-optchain icon indicating copy to clipboard operation
ts-optchain copied to clipboard

Add then() hook which returns null

Open dko-slapdash opened this issue 5 years ago • 1 comments

Hi.

This line: https://github.com/rimeto/ts-optchain/blob/734afe9c258e0cbd68b41178e445f21dc187281c/src/proxy/index.ts#L17

The essence is that oc() object cannot be currently returned as a Promise (see StackOverflow link below).

So to work-around, I had to wrap the oc() proxy into one more proxy which says that there is no then() hook defined explicitly:

  async json<TRes>() {
    const json = await (await this.fetch()).json();
    const ocProxy = oc(json as TRes);
    // This is crazy, but no-one can return Promise<Proxy> and live...
    // Because await calls Proxy's then() hook which doesn't exist in oc().
    // https://stackoverflow.com/a/53890904
    return new Proxy(ocProxy, {
      get: (target, key) => (key == "then" ? null : (target as any)[key])
    }) as typeof ocProxy;
  }
...
const res = await obj.json<{xyz: string}>();
console.log(res.xyz()); // hangs if json() doesn't do the trick and just returns the oc()

There could be a simple fix to oc() by just checking key for "then" - the same way as in the example above.

dko-slapdash avatar May 11 '19 01:05 dko-slapdash

I was about to create a similar ticket, returning oc from a promise breaks the promise. Maybe something with a condition like data instanceof Promise.

loucyx avatar May 26 '19 16:05 loucyx