upload/model/File.js

/**
 * @module flitter-upload/model/File
 */

const { Model } = require('flitter-orm')

/**
 * Represents a file stored in some backend and
 * contains information about that file, and helper
 * methods that can be used to access it.
 * @extends module:flitter-orm/src/model/Model~Model
 */
class File extends Model {
    /**
     * Defines the services required by this model.
     * @returns {Array<string>}
     */
    static get services() {
        return [...super.services, 'upload']
    }

    /**
     * Get the schema definition for this model. Provides the following fields:
     * - original_name (String) - the original name of the file
     * - upload_name (String) - the name of the file as it exists in the store
     * - mime_type (String)
     * - upload_date (Date = now)
     * - store (String) - the name of the store this file exists in
     * - store_id (String) - some unique identifier for this file used by the store
     * - discarded (Boolean = false) - if true, the file has been "discarded" by the user
     * @returns {{store_id: StringConstructor, discarded: {default: boolean, type: BooleanConstructor}, mime_type: StringConstructor, original_name: StringConstructor, store: StringConstructor, upload_name: StringConstructor, upload_date: {default: (function(): Date), type: DateConstructor}}}
     */
    static get schema() {
        return {
            original_name: String,
            upload_name: String,
            mime_type: String,
            upload_date: { type: Date, default: () => new Date },
            store: String,
            store_id: String,
            discarded: { type: Boolean, default: false },
        }
    }

    /**
     * Get the upload store associated with this file.
     * @returns {module:flitter-upload/store/Store~Store}
     */
    provider() {
        return this.upload.get(this.store)
    }

    /**
     * Send the file represented by this model as the response.
     * @param {express/response} response
     * @returns {Promise<void>}
     */
    async send(response) {
        await this.provider().send_file(this, response)
    }
}

module.exports = exports = File