All files / src/query create_accessor.tsx

82.6% Statements 57/69
51.21% Branches 21/41
90.9% Functions 10/11
82.08% Lines 55/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 2471x                     1x                                         9x 9x     9x 9x     9x         9x     9x     9x     9x     9x           9x               9x                 8x   8x   8x 7x     7x 2x               5x                 5x     8x 8x           9x           8x     8x   8x       8x 8x         8x 8x         8x             8x     8x             8x 8x               8x           9x                     20x     20x   20x     20x 20x 12x       12x   8x             8x       8x   5x 5x         8x 8x                 8x           9x                  
import { suspend } from '../suspend';
import {
  AccessorQueryCacheStore,
  AccessorQueryConfiguration,
  AccessorQueryContext,
  AccessorQueryResultCacheSetResult,
} from './types';
 
/**
 * Creates a query accessor.
 */
export const createAccessor = <
  TCache extends AccessorQueryCacheStore,
  TQueryRequest,
  TQueryResponse,
  TData,
>(
  configuration: AccessorQueryConfiguration<
    TCache,
    TQueryRequest,
    TQueryResponse,
    TData
  >,
): {
  configuration: AccessorQueryConfiguration<
    TCache,
    TQueryRequest,
    TQueryResponse,
    TData
  >;
  context: AccessorQueryContext<TCache, TQueryRequest, TQueryResponse, TData>;
} => {
  const { debug, cache, query } = configuration;
  const queryName = query.name;
 
  // Validate configuration.
  (() => {
    Iif (typeof debug !== 'boolean') {
      throw new Error('Invalid `debug` value. Must be a boolean.');
    }
    Iif (cache.duration <= 0) {
      throw new Error(
        'Invalid `cache.duration` value. Must be an integer greater than zero.',
      );
    }
    Iif (typeof cache.id !== 'function') {
      throw new Error('Invalid `cache.id` value. Must be a function.');
    }
    Iif (typeof cache.get !== 'function') {
      throw new Error('Invalid `cache.get` value. Must be a function.');
    }
    Iif (typeof cache.set !== 'function') {
      throw new Error('Invalid `cache.set` value. Must be a function.');
    }
    Iif (typeof cache.clear !== 'function') {
      throw new Error('Invalid `cache.clear` value. Must be a function.');
    }
    Iif (typeof cache.isPrimableFromCache !== 'boolean') {
      throw new Error(
        'Invalid `cache.isPrimableFromCache` value. Must be a boolean.',
      );
    }
 
    Iif (typeof query !== 'function') {
      throw new Error('Invalid `query` value. Must be a function.');
    }
  })();
 
  /*
   * Query promise.
   */
  const queryPromise = ({
    getCacheStore,
    cacheId,
    args,
  }: {
    getCacheStore: () => TCache;
    cacheId: string;
    args: TQueryRequest;
  }): Promise<AccessorQueryResultCacheSetResult<TData>> => {
    const state = { isQueryFinished: false };
    const promise: Promise<AccessorQueryResultCacheSetResult<TData>> =
      (async () => {
        // Execute query.
        const response = await query(args);
        state.isQueryFinished = true;
 
        // Handle query errors.
        if (response.status !== 200 || response.error || !response.data) {
          throw new Error(
            `(${response.status}) Response failed${
              response.error ? `: ${response.error}` : '.'
            }`,
          );
        }
 
        // Set query promise result cache.
        const cacheSetResult = cache.set({
          cacheId: cacheId,
          args,
          cache: getCacheStore,
          request: (args: TQueryRequest) =>
            requestQueryPromise(getCacheStore, args),
          response: { status: response.status, data: response.data },
        });
 
        return cacheSetResult;
      })();
    // TODO: Make a type that extends promise that works with async return types.
    (promise as any).state = state;
    return promise;
  };
 
  /*
   * Request query promise.
   */
  const requestQueryPromise = (
    getCacheStore: () => TCache,
    args: TQueryRequest,
  ): Promise<AccessorQueryResultCacheSetResult<TData>> => {
    const {
      dataAccess: { set, query: cacheQuery },
    } = getCacheStore();
 
    // Get the cache id for this request.
    const cacheId = cache.id({ args });
 
    debug &&
      console.log(`[data-access:${queryName}:${cacheId}] read query cache.`);
 
    // Does our library have any errors that occurred?
    const cacheQueryRequest = cacheQuery.get(cacheId);
    Iif (cacheQueryRequest instanceof Error) {
      throw cacheQueryRequest;
    }
 
    // Do we have an existing query request promise in the cache?
    const cacheQueryPromise = cacheQueryRequest?.promise;
    Iif (cacheQueryPromise) {
      debug &&
        console.log(`[data-access:${queryName}:${cacheId}] query cache found.`);
      return cacheQueryPromise;
    } else {
      debug &&
        console.log(
          `[data-access:${queryName}:${cacheId}] query cache *not* found.`,
        );
    }
 
    // Execute request query promise.
    debug &&
      console.log(`[data-access:${queryName}:${cacheId}] execute query.`);
    const promise: Promise<AccessorQueryResultCacheSetResult<TData>> =
      queryPromise({
        getCacheStore,
        cacheId,
        args,
      });
 
    // Cache request query promise.
    set(({ dataAccess: { query: cacheQuery } }) => {
      cacheQuery.set(cacheId, {
        cacheTimeToRefresh: Date.now() + cache.duration,
        // NOTE: This is stored in cache with a generic type of 'any'.
        //       Not sure why typescript doesn't throw here without type casting.
        promise,
      });
    });
 
    return promise;
  };
 
  /*
   * Suspend request query.
   */
  const suspenseRequestQuery = ({
    getCacheStore,
    onDone,
    args,
  }: {
    getCacheStore: () => TCache;
    onDone?: () => void;
    args: TQueryRequest;
  }): (() => AccessorQueryResultCacheSetResult<TData>) => {
    const {
      dataAccess: { set, suspense: cacheSuspense },
    } = getCacheStore();
 
    // Do we have an existing request in the cache?
    const cacheId = cache.id({ args });
 
    debug &&
      console.log(`[data-access:${queryName}:${cacheId}] read suspense cache.`);
 
    const cacheRequestSuspense = cacheSuspense.get(cacheId);
    if (cacheRequestSuspense) {
      debug &&
        console.log(
          `[data-access:${queryName}:${cacheId}] suspense cache found.`,
        );
      return cacheRequestSuspense;
    } else {
      debug &&
        console.log(
          `[data-access:${queryName}:${cacheId}] suspense cache *not* found.`,
        );
    }
 
    // Execute query request in suspense format.
    debug &&
      console.log(
        `[data-access:${queryName}:${cacheId}] expecute query promise.`,
      );
    const suspense: () => AccessorQueryResultCacheSetResult<TData> = suspend(
      requestQueryPromise(getCacheStore, args).then(result => {
        onDone && onDone();
        return result;
      }),
    );
 
    // Cache suspended request query.
    set(({ dataAccess: { suspense: cacheSuspense } }) => {
      cacheSuspense.set(
        cacheId,
        // NOTE: This is stored in cache with a generic type of 'any'.
        //       Not sure why typescript doesn't throw here without type casting.
        suspense,
      );
    });
 
    // Return suspense!
    return suspense;
  };
 
  /*
   * Accessor definition.
   */
  return {
    configuration,
    context: {
      queryName,
      requestQueryPromise,
      suspenseRequestQuery,
    },
  };
};