All files / lib/storage utils.ts

100% Statements 17/17
71.42% Branches 10/14
100% Functions 6/6
100% Lines 16/16

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                              2x 1x     1x                                                                   2x   2x                 2x                                                         1x                 1x                       3x 1x     2x   2x                                         2x   2x   1x             47x    
import type { BinaryStorageLocator } from './types.js';
import type { Tables } from '$lib/database.js';
import type { DatabaseHandle, IDBDatabaseType } from '$lib/idb.svelte.js';
 
import { pick } from '$lib/utils.js';
 
import { binaryStorage } from './index.js';
 
/**
 * Get the size in bytes of the given database object
 */
export async function byteSizeOfObject<Table extends BinaryStorageLocator['area']>(
	table: Table,
	object: Pick<IDBDatabaseType[Table]['value'], 'sessionId' | 'filename' | 'bytes'>
): Promise<number> {
	if (object.bytes !== 'migrated') {
		return object.bytes.byteLength;
	}
 
	return binaryStorage.size({
		area: table,
		sessionId: 'sessionId' in object ? object.sessionId : undefined,
		name: object.filename,
	});
}
 
type CreateBytesObjectFields<Table extends BinaryStorageLocator['area']> = Pick<
	IDBDatabaseType[Table]['value'],
	'filename' | 'sessionId'
>;
 
/**
 * Stores bytes in binary storage for a to-be-created database object
 *
 * ```ts
 * await tables.ImageFile.add({
 * 		dimensions: { ... },
 * 		...(await createBytes("ImageFile", {
 * 			filename,
 * 			bytes,
 *		 	sessionId
 * 		})),
 * })
 * ```
 *
 * @param table
 * @param filename
 * @param content
 */
export async function createBytes<Table extends BinaryStorageLocator['area']>(
	table: Table,
	input: CreateBytesObjectFields<Table> & { bytes: ArrayBuffer; type: `image/${string}` }
): Promise<CreateBytesObjectFields<Table> & { bytes: 'migrated' }> {
	console.debug('createBytes', table, input);
 
	const written = await binaryStorage.create(
		{
			area: table,
			sessionId: 'sessionId' in input ? input.sessionId : undefined,
			name: input.filename,
		},
		pick(input, 'type', 'bytes')
	);
 
	return {
		...input,
		filename: written.name,
		bytes: 'migrated',
	};
}
 
/**
 * Stores bytes for the given database object in binary storage.
 *
 * **⚠️	This function does not handle filename conflicts. Don't use it to create new database objects**
 *
 * Returns `"migrated"` for ergonomics:
 *
 * ```ts
 * await tables.ImageFile.put({
 * 		filename: ...
 * 		dimensions: { ... },
 * 		bytes: await storeBytes(...), // sets the database field to "migrated"
 * })
 * ```
 *
 * Writes the binary content of the object in binary storage.
 */
export async function storeBytes<Table extends BinaryStorageLocator['area']>(
	table: Table,
	object: (typeof Tables)[Table]['inferIn'],
	content: ArrayBuffer
): Promise<'migrated'> {
	await binaryStorage.write(
		{
			area: table,
			sessionId: 'sessionId' in object ? object.sessionId : undefined,
			name: object.filename,
		},
		content
	);
 
	return 'migrated';
}
 
/**
 * Access bytes of a table object storing binary data in its `bytes` field.
 * Handles objects that have their binary data stored in the binary storage
 * @param object the table
 */
export async function accessBytes<Table extends BinaryStorageLocator['area']>(
	table: Table,
	object: Pick<(typeof Tables)[Table]['inferIn' | 'inferOut'], 'sessionId' | 'filename' | 'bytes'>
): Promise<ArrayBuffer> {
	if (object.bytes !== 'migrated') {
		return object.bytes;
	}
 
	console.debug(`accessBytes ${table}`, object);
 
	return binaryStorage.bytes({
		area: table,
		sessionId: 'sessionId' in object ? object.sessionId : undefined,
		name: object.filename,
	});
}
 
/**
 * Get an object from a table and resolves its `bytes` field to an ArrayBuffer
 * by reading in the binary storage if necessary
 * @param table
 * @param id
 * @returns the object (undefined if not found), with the bytes field always a {@link ArrayBuffer}
 */
export async function resolveObjectWithBytes<Table extends BinaryStorageLocator['area']>(
	db: DatabaseHandle,
	table: Table,
	id: string
): Promise<
	undefined | (Omit<IDBDatabaseType[NoInfer<Table>]['value'], 'bytes'> & { bytes: ArrayBuffer })
> {
	const object = await db.get(table, id);
 
	if (!object) return undefined;
 
	return {
		...object,
		bytes: await accessBytes(table, object),
	};
}
 
export function locatorToPath(locator: BinaryStorageLocator): string {
	return [locator.area, locator.sessionId, locator.name].filter(Boolean).join('/');
}