@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
300 lines • 12.5 kB
JavaScript
import { clampMediaListLimit, decodeMediaCursor, encodeMediaCursor, } from '../media_store.js';
import { assertSafeIdentifier, assertSchema, createMediaTables, detectDialect, ensureMediaTenantColumn, hasMediaTenantColumn, inspectSchemaTables, qualifiedTable, } from './lucid-schema.js';
/** Thrown when tenancy is on and the `media` table has no `tenant_id` column. */
export class MediaTenancySchemaError extends Error {
code = 'E_MEDIA_TENANCY_SCHEMA';
constructor(table) {
super(`-agora/media: tenancy is on but the "${table}" table has no tenant_id column. Run \`node ace media:publish-migration tenancy\` and \`node ace migration:run\`, or set \`tenancy: false\` in config/media.ts.`);
this.name = 'MediaTenancySchemaError';
}
}
/**
* Lucid-backed {@link MediaStore}. Persists media records in a `media` table via `@adonisjs/lucid`'s
* query builder (Knex), so it works across SQLite / Postgres / MySQL. JSON payloads
* (`custom_properties`, `conversions`) are stored as TEXT and timestamps as epoch-ms integers, so the
* schema is portable across engines.
*
* The `media` table is auto-created on first use (`autoCreateSchema`, default `true`) — the
* ecosystem convention, same as `@adonis-agora/authz` and `@adonis-agora/durable`. An app that
* prefers explicit control sets `autoCreateSchema: false` and publishes the migration via
* `node ace configure @adonis-agora/media` (or calls {@link createMediaTables} from a migration).
*/
export class LucidMediaStore {
db;
tenantFiltering = true;
table;
/** The configured database schema, or `undefined` for the connection's current one. */
schema;
/** {@link table} as the query builder takes it (`schema.table` when a schema is set). */
qualified;
connectionName;
autoCreate;
tenantColumn;
schemaReady;
constructor(db, options = {}) {
this.db = db;
this.table = options.table ?? 'media';
this.connectionName = options.connectionName;
this.autoCreate = options.autoCreateSchema !== false;
this.tenantColumn = options.tenantColumn === true;
this.schema =
options.schema === undefined
? undefined
: assertSchema(options.schema, this.dialect(), 'stores.lucid()');
// With a schema the table must be a bare name: `a.b` would make a three-part reference.
if (this.schema !== undefined)
assertSafeIdentifier(this.table);
this.qualified = qualifiedTable(this.table, this.schema);
}
/** The connection's dialect name, when it can be read without a query. */
dialect() {
try {
return detectDialect(this.client());
}
catch {
return undefined;
}
}
/** The options every schema helper takes: the table and, when set, the schema. */
schemaOptions() {
return { table: this.table, ...(this.schema !== undefined ? { schema: this.schema } : {}) };
}
client() {
return this.connectionName ? this.db.connection(this.connectionName) : this.db.connection();
}
query() {
return this.client().from(this.qualified);
}
/** Ensure the schema exists before the first operation, once per store instance. */
async ready() {
if (!this.autoCreate && !this.tenantColumn)
return;
if (!this.schemaReady) {
this.schemaReady = (this.autoCreate ? this.ensureSchema() : this.assertTenantColumn()).catch((error) => {
// Not cached: a migration run later in the same process is picked up on the next call.
this.schemaReady = undefined;
throw error;
});
}
return this.schemaReady;
}
async assertTenantColumn() {
if (!(await hasMediaTenantColumn(this.client(), this.schemaOptions()))) {
throw new MediaTenancySchemaError(this.qualified);
}
}
/** Whether the table has the `tenant_id` column tenancy needs. */
async hasTenantColumn() {
return hasMediaTenantColumn(this.client(), this.schemaOptions());
}
/**
* Where the configured {@link schema} stands, for `agora:doctor`: whether it exists, whether the
* table is in it, and whether this connection may write to it. `null` without a schema.
*/
async inspectSchema() {
if (this.schema === undefined)
return null;
return inspectSchemaTables(this.client(), this.schema, [this.table]);
}
/**
* Create the `media` table (idempotent). Delegates to the standalone {@link createMediaTables}
* so the auto-create path and a migration-based one run identical DDL.
*/
async ensureSchema() {
// On the store's own connection: the `Database` facade would run the DDL on the default one.
const client = this.client();
await createMediaTables(client, this.schemaOptions());
if (this.tenantColumn)
await ensureMediaTenantColumn(client, this.schemaOptions());
}
async save(record) {
await this.ready();
const row = toRow(record, this.tenantColumn);
// Single atomic upsert (portable Knex `INSERT ... ON CONFLICT (id) DO UPDATE`) instead of a
// racy read-then-branch: concurrent saves of the same id can't interleave into a lost write.
await this.client().table(this.qualified).insert(row).onConflict('id').merge();
return { ...record };
}
async find(id) {
await this.ready();
const row = (await this.query().where('id', id).first());
return row ? fromRow(row) : null;
}
async listByOwner(ownerType, ownerId, collection) {
await this.ready();
let q = this.query().where('owner_type', ownerType).where('owner_id', ownerId);
if (collection !== undefined)
q = q.where('collection', collection);
const rows = (await q.orderBy('order', 'asc'));
return rows.map(fromRow);
}
async listByOwnerPaged(ownerType, ownerId, options = {}) {
if (options.collections !== undefined && options.collections.length === 0) {
return { items: [], nextCursor: null };
}
return this.list({
ownerType,
ownerId,
...(options.cursor !== undefined ? { cursor: options.cursor } : {}),
...(options.limit !== undefined ? { limit: options.limit } : {}),
...(options.tenantIds !== undefined ? { tenantIds: options.tenantIds } : {}),
...(options.collections !== undefined ? { collectionIn: options.collections } : {}),
});
}
async list(options = {}) {
await this.ready();
const limit = clampMediaListLimit(options.limit);
let q = this.query();
if (options.collectionIn !== undefined)
q = q.whereIn('collection', [...options.collectionIn]);
if (options.ownerType !== undefined)
q = q.where('owner_type', options.ownerType);
if (options.ownerId !== undefined)
q = q.where('owner_id', options.ownerId);
if (options.collection !== undefined)
q = q.where('collection', options.collection);
if (options.prefix !== undefined && options.prefix !== '') {
q = q.where('path', 'like', `${options.prefix}%`);
}
if (this.tenantColumn && options.tenantIds !== undefined) {
q = whereTenantIn(q, options.tenantIds);
}
// Keyset pagination on the (created_at desc, id desc) ordering: resume strictly *after* the cursor
// row, so pages don't drift or duplicate when rows are inserted concurrently.
const cursor = decodeMediaCursor(options.cursor);
if (cursor) {
q = q.where((builder) => {
builder
.where('created_at', '<', cursor.createdAt)
.orWhere((eq) => eq.where('created_at', cursor.createdAt).where('id', '<', cursor.id));
});
}
// Fetch one extra row to detect whether a further page exists without a second COUNT query.
const rows = (await q
.orderBy('created_at', 'desc')
.orderBy('id', 'desc')
.limit(limit + 1));
const hasMore = rows.length > limit;
const page = hasMore ? rows.slice(0, limit) : rows;
const items = page.map(fromRow);
const last = page[page.length - 1];
return {
items,
nextCursor: hasMore && last
? encodeMediaCursor({ createdAt: Number(last.created_at), id: last.id })
: null,
};
}
async delete(id) {
await this.ready();
await this.query().where('id', id).delete();
}
async collectionTotals(options = {}) {
await this.ready();
let q = this.query();
if (this.tenantColumn && options.tenantIds !== undefined) {
q = whereTenantIn(q, options.tenantIds);
}
const rows = (await q
.select('collection')
.count('* as count')
.sum('size as sum_size')
.max('created_at as newest')
.groupBy('collection')
.orderBy('newest', 'desc'));
return rows.map((row) => ({
collection: row.collection,
count: Number(row.count),
sumSize: Number(row.sum_size ?? 0),
}));
}
async listTenants() {
if (!this.tenantColumn)
return [];
await this.ready();
const rows = (await this.query()
.distinct('tenant_id')
.whereNotNull('tenant_id')
.orderBy('tenant_id', 'asc')
.limit(1000));
return rows.map((row) => String(row.tenant_id));
}
async nextOrder(ownerType, ownerId, collection) {
await this.ready();
const row = (await this.query()
.where('owner_type', ownerType)
.where('owner_id', ownerId)
.where('collection', collection)
.max('order as max_order')
.first());
const max = row?.max_order;
return max === null || max === undefined ? 0 : Number(max) + 1;
}
}
/** `tenant_id IN (…)`, with `null` standing for `tenant_id IS NULL`; an empty list matches nothing. */
// biome-ignore lint/suspicious/noExplicitAny: Knex's chainable builder type.
function whereTenantIn(q, tenantIds) {
const ids = tenantIds.filter((id) => id !== null);
const withNull = tenantIds.includes(null);
return q.where((builder) => {
if (ids.length === 0 && !withNull) {
builder.whereRaw('1 = 0');
return;
}
if (ids.length > 0)
builder.whereIn('tenant_id', ids);
if (withNull)
builder.orWhereNull('tenant_id');
});
}
function toRow(record, tenantColumn) {
return {
...(tenantColumn ? { tenant_id: record.tenantId ?? null } : {}),
id: record.id,
owner_type: record.ownerType,
owner_id: record.ownerId,
collection: record.collection,
name: record.name,
file_name: record.fileName,
mime_type: record.mimeType,
size: record.size,
disk: record.disk,
path: record.path,
order: record.order,
custom_properties: JSON.stringify(record.customProperties ?? {}),
conversions: JSON.stringify(record.conversions ?? {}),
created_at: record.createdAt.getTime(),
updated_at: record.updatedAt.getTime(),
};
}
function fromRow(row) {
return {
id: row.id,
ownerType: row.owner_type,
ownerId: row.owner_id,
collection: row.collection,
name: row.name,
fileName: row.file_name,
mimeType: row.mime_type,
size: Number(row.size),
disk: row.disk,
path: row.path,
order: Number(row.order),
customProperties: parseJson(row.custom_properties, {}),
conversions: parseJson(row.conversions, {}),
createdAt: new Date(Number(row.created_at)),
updatedAt: new Date(Number(row.updated_at)),
...(row.tenant_id !== undefined ? { tenantId: row.tenant_id } : {}),
};
}
function parseJson(value, fallback) {
if (!value)
return fallback;
try {
return JSON.parse(value);
}
catch {
return fallback;
}
}
//# sourceMappingURL=lucid.js.map