/* @flow * * Create a RethinkDB query and cache it's result in a TagCache * * Usage: * * const getThreadById = createReadQuery({ * // NOTE: No .run() at the end of the query!!! * query: (threadId: string) => db.table('threads').get(threadId), * tags: (threadId: string) => (thread: ?DBThread) => thread ? [thread.id, thread.communityId, thread.channelId] : [], * }); * * const updateUser = createWriteQuery({ * // NOTE: .run() at the end of the query * query: (userId: string, data: Object) => db.table('users').get(userId).update(data).run(), * invalidateTags: (userId: string) => () => [userId] * }); */ import { READ_RUN_ERROR, WRITE_RUN_ERROR } from './constants'; type RethinkDBQuery = { toString: Function, run: () => Promise, }; type ProcessFn = (data: O) => Promise<*> | *; type TagsFn = (data: O) => Array; type CreateReadQueryInput = $Exact<{ query: RethinkDBQuery, process?: ProcessFn, tags: TagsFn, }>; type CreateQueryCallback = (...args: I) => O; export const createReadQuery = (callback: any) => { return async (...args: any) => { const input = callback(...args); if (typeof input.query.run !== 'function') throw new Error(READ_RUN_ERROR); // const queryString = input.query.toString(); // const cached = await queryCache.get(queryString); // if (cached) { // CACHED_RESULTS++; // return cached; // } const result = await input.query .run() .then(input.process ? input.process : res => res); // const tags = input.tags(result).filter(Boolean); // await queryCache.set(queryString, result, tags); return result; }; }; type CreateWriteQueryInput = $Exact<{ query: Promise, invalidateTags: TagsFn, }>; export const createWriteQuery = , O: *>(callback: any) => { return async (...args: I) => { const input = callback(...args); const result = await input.query; if (typeof result.run === 'function') throw new Error(WRITE_RUN_ERROR); // const tags = input.invalidateTags(result).filter(Boolean); // await queryCache.invalidate(...tags); return result; }; };