hasOneAttached gives a record a named file, such as a user's avatar or an
invoice's PDF, without hand-written blob code. The file bytes go to a Disk
(the jsails/filesystem contract, implemented by LocalDisk, S3Disk, and
MemoryDisk in @jsails/filesystem), and a row in the framework-owned
jsails_attachment table records where it is. Both come from jsails/database
(and the root jsails entry).
Setup
Add the attachment entity to your data source and create its table through the normal schema history:
// jsails.database.js
import { JsailsDataSource, activeStorageEntities, readDatabaseEnvironment } from 'jsails';
export default new JsailsDataSource({
...readDatabaseEnvironment(),
entities: [...activeStorageEntities],
});
jsails db:push --config jsails.database.js
activeStorageEntities holds the one entity, JsailsAttachment; list it next
to any hand-written entities. The table is never created at runtime.
Declaring an attachment
import { hasOneAttached } from 'jsails/database';
import { LocalDisk } from '@jsails/filesystem';
const avatar = hasOneAttached({
disk: new LocalDisk({ root: 'storage/avatars', maxBytes: 1024 * 1024 * 1024 }),
name: 'avatar',
recordType: 'User',
dataSource,
urlPrefix: '/avatars', // optional; where the disk's files are served
});
recordTypeandnamescope every row, soavataronUserandavataronTeamnever collide.dataSourceis the initialized TypeORM data source that ownsjsails_attachment. It is passed in explicitly; there is no global registry.urlPrefixonly builds URLs. Serving the files at that prefix (a public directory, a CDN in front of the bucket, or a route that checks access) is up to you. Without it,url()returnsnull.
Attaching, reading, detaching
The handle has three functions; each takes the record as { id } with a
numeric id.
await avatar.detach(user); // replace: remove the previous file first
const attachment = await avatar.attach(user, bytes, 'image/png');
attachment.byteSize; // also: id, key, contentType, recordType, recordId, name, createdAt
await avatar.url(user); // '/avatars/user/7/avatar_3f9c…' or null
await avatar.detach(user); // deletes the blob, then the row; a no-op when absent
attach(record, data, contentType)writesdata(aUint8Array) to the disk under<recordtype>/<id>/<name>_<random>, then saves the row. The random 12-byte suffix makes every key unique, so a new file never overwrites an old one in a cache or CDN.attachadds a row; it does not remove an existing attachment. Calldetachfirst when replacing a file, or the old blob and row remain andurlmay return either one.contentTypeis stored as given and is not checked against the bytes. Validate the type and size of untrusted uploads before attaching (a server-componentuploadspolicy does both; see Forms and Uploads), and serve user files withX-Content-Type-Options: nosniff.- The disk write and the row insert are separate steps, not one transaction. If the insert fails, the blob stays on the disk without a row.
attach,detach, andurlraise no errors of their own; disk and database errors propagate unchanged.ActiveStorageErroris exported for themissing_data_sourcecode but is not currently thrown.
Testing
MemoryDisk from @jsails/filesystem keeps blobs in memory, so a test needs
only a database for the rows (see Testing).
Next steps
- Forms and Uploads — getting a file from the browser.
- Filesystem — the disk contract and implementations.
- Models — the Active Record layer.