All files / apps/huella-legal/layers/articles/server/adapters netlify.ts

100% Statements 24/24
100% Branches 10/10
100% Functions 4/4
100% Lines 21/21

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              1x   2x     1x 9x 9x     3x   1x         1x         6x   6x   4x 4x   3x   1x   1x         1x 3x   3x   2x 2x   1x      
import { getDeployStore, type Store } from "@netlify/blobs";
 
interface Saved<T> {
    savedAt: number;
    value: T;
}
 
const warn = (action: string, name: string, key: string, error: unknown): void => {
    // eslint-disable-next-line no-console -- a failed read or save leaves no other trace
    console.warn(`[blobs] Could not ${action} ${name}/${key}`, error);
};
 
const openStore = (name: string): Store | undefined => {
    try {
        return getDeployStore(name);
    } catch (error) {
        // Off Netlify (dev, CI, e2e) there is no Blobs context, and nothing is saved
        if ((error as Error).name === "MissingBlobsEnvironmentError") return undefined;
 
        throw error;
    }
};
 
/** Reads what this deploy saved under `key` less than `maxAge` seconds ago, if anything. */
export const readSaved = async <T>(
    name: string,
    key: string,
    maxAge: number,
): Promise<T | undefined> => {
    const store = openStore(name);
 
    if (!store) return undefined;
 
    try {
        const saved = (await store.get(key, { type: "json" })) as Saved<T> | null;
 
        return saved && Date.now() - saved.savedAt < maxAge * 1000 ? saved.value : undefined;
    } catch (error) {
        warn("read", name, key, error);
 
        return undefined;
    }
};
 
/** Saves `value` under `key` for this deploy, resolving once it is written. */
export const save = async (name: string, key: string, value: unknown): Promise<void> => {
    const store = openStore(name);
 
    if (!store) return;
 
    try {
        await store.setJSON(key, { savedAt: Date.now(), value } satisfies Saved<unknown>);
    } catch (error) {
        warn("save", name, key, error);
    }
};