|
1 |
| -import { Array, ArrayMetadata, Chunk, DataType } from "@zarrita/core"; |
| 1 | +import { Array as ZarrArray, Chunk, DataType } from "@zarrita/core"; |
2 | 2 | import VolumeCache, { CacheData } from "../../VolumeCache";
|
3 |
| -import { AbsolutePath, Readable } from "@zarrita/storage"; |
| 3 | +import { Readable } from "@zarrita/storage"; |
4 | 4 | import { pathIsToMetadata } from "./utils";
|
5 | 5 |
|
6 |
| -const ZARR_EXTS = [".zarray", ".zgroup", ".zattrs", "zarr.json"]; |
7 |
| - |
8 | 6 | const isChunk = (data: CacheData): data is Chunk<DataType> => (data as Chunk<DataType>).data !== undefined;
|
9 | 7 |
|
10 |
| -export default class CachingArray<T extends DataType, Store extends Readable = Readable> extends Array<T, Store> { |
11 |
| - constructor(store: Store, path: AbsolutePath, metadata: ArrayMetadata<T>, private cache?: VolumeCache) { |
12 |
| - super(store, path, metadata); |
13 |
| - } |
14 |
| - |
15 |
| - async getChunk(coords: number[], opts?: Parameters<Store["get"]>[1]): Promise<Chunk<T>> { |
16 |
| - if (!this.cache || pathIsToMetadata(this.path)) { |
17 |
| - return super.getChunk(coords, opts); |
| 8 | +export default function cachingArray<T extends DataType, Store extends Readable = Readable>( |
| 9 | + array: ZarrArray<T, Store>, |
| 10 | + cache: VolumeCache |
| 11 | +): ZarrArray<T, Store> { |
| 12 | + const getChunk = async (coords: number[], opts?: Parameters<Store["get"]>[1]): Promise<Chunk<T>> => { |
| 13 | + if (pathIsToMetadata(array.path)) { |
| 14 | + return array.getChunk(coords, opts); |
18 | 15 | }
|
19 | 16 |
|
20 |
| - const trailingSlash = this.path.endsWith("/") ? "" : "/"; |
21 |
| - const fullKey = this.path + trailingSlash + coords.join(","); |
22 |
| - const cacheResult = this.cache.get(fullKey); |
| 17 | + const trailingSlash = array.path.endsWith("/") ? "" : "/"; |
| 18 | + const fullKey = array.path + trailingSlash + coords.join(","); |
| 19 | + const cacheResult = cache.get(fullKey); |
23 | 20 | if (cacheResult && isChunk(cacheResult)) {
|
24 | 21 | return cacheResult;
|
25 | 22 | }
|
26 | 23 |
|
27 |
| - const result = await super.getChunk(coords, opts); |
28 |
| - this.cache.insert(fullKey, result); |
| 24 | + const result = await array.getChunk(coords, opts); |
| 25 | + cache.insert(fullKey, result); |
29 | 26 | return result;
|
30 |
| - } |
| 27 | + }; |
| 28 | + |
| 29 | + return new Proxy(array, { |
| 30 | + get: (target, prop, reciever) => (prop === "getChunk" ? getChunk : Reflect.get(target, prop, reciever)), |
| 31 | + }); |
31 | 32 | }
|
0 commit comments