File size: 2,197 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* @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<O> = {
  toString: Function,
  run: () => Promise<O>,
};

type ProcessFn<I, O> = (data: O) => Promise<*> | *;
type TagsFn<I, O> = (data: O) => Array<?string>;

type CreateReadQueryInput<I, O> = $Exact<{
  query: RethinkDBQuery<O>,
  process?: ProcessFn<I, O>,
  tags: TagsFn<I, O>,
}>;

type CreateQueryCallback<I, O> = (...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<I, O> = $Exact<{
  query: Promise<O>,
  invalidateTags: TagsFn<I, O>,
}>;

export const createWriteQuery = <I: Array<*>, 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;
  };
};