orm/src/model/CursorBuilder.js

/**
 * @module flitter-orm/src/model/CursorBuilder
 */

/**
 * Wrapper for building up layers to apply to a cursor when it is created.
 */
class CursorBuilder {
    /**
     * Functions that modify the cursor, in order.
     * The functions take one parameter, the cursor, and return nothing.
     * @type {Array<function>}
     */
    layers = []

    /**
     * Apply the builder's layers to a cursor.
     * @param {mongodb/Cursor} cursor
     * @returns {mongodb/Cursor}
     */
    apply(cursor) {
        for ( const layer of this.layers ) {
            layer(cursor)
        }

        return cursor
    }

    /**
     * Add a layer that sorts the cursor.
     * @param {Array<string>} sorts - array of sorts - e.g. '+field'/'-field'/'field'
     */
    sort(sorts) {
        const sort_obj = {}
        for ( const sort of sorts ) {
            if ( sort.startsWith('-') ) {
                sort_obj[sort.substr(1)] = -1
            } else if ( sort.startsWith('+') ) {
                sort_obj[sort.substr(1)] = 1
            } else {
                sort_obj[sort] = 1
            }
        }

        this.layers.push(cursor => {
            cursor.sort(sort_obj)
        })
    }

    /**
     * Add a layer that limits the cursor.
     * @param {number} to - max number of records
     */
    limit(to) {
        this.layers.push(cursor => {
            cursor.limit(to)
        })
    }

    /**
     * Add a layer that applies a filter to the cursor.
     * @param {module:flitter-orm/src/filter/Filter~Filter} filter
     */
    filter(filter) {
        this.layers.push(cursor => {
            cursor.filter(filter.write())
        })
    }
}

module.exports = exports = CursorBuilder