@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
139 lines • 5.83 kB
JavaScript
/**
* The media schema for the Lucid store, as standalone functions.
*
* By default {@link LucidMediaStore} auto-creates the `media` table on first use
* (`autoCreateSchema`, the ecosystem convention — a lib owns its own schema, same
* as `@adonis-agora/authz`'s `createAuthzTables` and `@adonis-agora/durable`'s
* `createDurableTables`). An app that prefers explicit control sets
* `autoCreateSchema: false` and calls {@link createMediaTables} from a Lucid
* migration instead. Both paths run the SAME DDL — the store's `ensureSchema`
* delegates here — so they never drift.
*/
/** The default table names for the Lucid store's media schema. */
export const MEDIA_TABLES = {
media: 'media',
};
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Reject any table name that is not a bare SQL identifier (these are interpolated, never bound). */
export function assertSafeIdentifier(id) {
if (!IDENT.test(id))
throw new Error(`@adonis-agora/media: unsafe SQL identifier: ${JSON.stringify(id)}`);
return id;
}
export function isPostgres(dialect) {
return !!dialect && /postgres|pg|redshift/i.test(dialect);
}
export function isMysql(dialect) {
return !!dialect && /mysql|mariadb/i.test(dialect);
}
/**
* Best-effort dialect name from a Lucid client; `undefined` when it can't be read.
*/
export function detectDialect(db) {
try {
const direct = db.dialect?.name;
if (typeof direct === 'string' && direct.length > 0)
return direct;
return db.connection?.()?.dialect?.name;
}
catch {
return undefined;
}
}
/** Resolve the effective table name, validating the identifier. */
function resolveTables(options) {
const t = { ...MEDIA_TABLES };
if (options.table !== undefined) {
assertSafeIdentifier(options.table);
t.media = options.table;
}
return t;
}
/**
* Create the `media` table (idempotent — `CREATE TABLE IF NOT EXISTS`). Safe to call
* from a Lucid migration `up()` or repeatedly at boot.
*
* The shape mirrors the migration published by `node ace configure @adonis-agora/media`:
* JSON payloads (`custom_properties`, `conversions`) are stored as TEXT — the store
* (de)serializes them — and timestamps as epoch-ms integers, so the schema is portable
* across SQLite / Postgres / MySQL.
*
* @param db a Lucid `Database` or connection client
* @param options.table optional table-name override (defaults to {@link MEDIA_TABLES})
*/
export async function createMediaTables(db, options = {}) {
const t = resolveTables(options);
const run = (sql) => db.rawQuery(sql);
await run(`CREATE TABLE IF NOT EXISTS ${t.media} (
id VARCHAR(255) PRIMARY KEY,
owner_type VARCHAR(255) NOT NULL,
owner_id VARCHAR(255) NOT NULL,
collection VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
file_name VARCHAR(255) NOT NULL,
mime_type VARCHAR(255) NOT NULL,
size BIGINT NOT NULL,
disk VARCHAR(255) NOT NULL,
path TEXT NOT NULL,
"order" INTEGER NOT NULL DEFAULT 0,
custom_properties TEXT,
conversions TEXT,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL
)`);
// `(owner_type, owner_id)` lookups use the leftmost prefix of the owner+collection index.
await run(`CREATE INDEX IF NOT EXISTS ${t.media}_owner_collection_idx ON ${t.media} (owner_type, owner_id, collection)`);
// The newest-first keyset `list()` pages on, unfiltered and per collection.
await run(`CREATE INDEX IF NOT EXISTS ${t.media}_created_idx ON ${t.media} (created_at, id)`);
await run(`CREATE INDEX IF NOT EXISTS ${t.media}_collection_created_idx ON ${t.media} (collection, created_at, id)`);
}
/**
* Drop the `media` table (idempotent — `DROP TABLE IF EXISTS`). For a migration `down()`.
*
* @param db a Lucid `Database` or connection client
* @param options.table optional table-name override (defaults to {@link MEDIA_TABLES})
*/
export async function dropMediaTables(db, options = {}) {
const t = resolveTables(options);
await db.rawQuery(`DROP TABLE IF EXISTS ${t.media}`);
}
/**
* Whether the `media` table has the `tenant_id` column tenancy needs (a zero-row probe query).
*
* @param db a Lucid `Database` or connection client
* @param options.table optional table-name override (defaults to {@link MEDIA_TABLES})
*/
export async function hasMediaTenantColumn(db, options = {}) {
const t = resolveTables(options);
try {
await db.rawQuery(`SELECT tenant_id FROM ${t.media} WHERE 1 = 0`);
return true;
}
catch {
return false;
}
}
/**
* Add the nullable `tenant_id` column and its `(tenant_id, owner_type, owner_id, collection)` index
* to the `media` table when missing (idempotent). Tenancy (organizations as tenants) stamps new
* files with it; existing rows stay `NULL`. Same DDL as the migration
* `node ace media:publish-migration tenancy` publishes.
*
* @param db a Lucid `Database` or connection client
* @param options.table optional table-name override (defaults to {@link MEDIA_TABLES})
*/
export async function ensureMediaTenantColumn(db, options = {}) {
const t = resolveTables(options);
if (!(await hasMediaTenantColumn(db, options))) {
await db.rawQuery(`ALTER TABLE ${t.media} ADD COLUMN tenant_id VARCHAR(255) NULL`);
}
// MySQL has no `CREATE INDEX IF NOT EXISTS`: a duplicate index there is reported and ignored.
try {
await db.rawQuery(`CREATE INDEX ${isMysql(detectDialect(db)) ? '' : 'IF NOT EXISTS '}${t.media}_tenant_owner_idx ON ${t.media} (tenant_id, owner_type, owner_id, collection)`);
}
catch (error) {
if (!/duplicate|exists/i.test(String(error?.message ?? error)))
throw error;
}
}
//# sourceMappingURL=lucid-schema.js.map