All files / src/lib/middleware session-db.ts

90.91% Statements 10/11
66.67% Branches 4/6
100% Functions 1/1
90.91% Lines 10/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46  46x 46x     46x             64x   64x 64x 64x               64x   64x                                   46x  
import { Knex } from 'knex';
import session from 'express-session';
import knexSessionStore from 'connect-session-knex';
import { RequestHandler } from 'express';
import { IUnleashConfig } from '../types/option';
import { hoursToMilliseconds } from 'date-fns';
 
function sessionDb(
    config: Pick<IUnleashConfig, 'session' | 'server' | 'secureHeaders'>,
    knex: Knex,
): RequestHandler {
    let store;
    const { db } = config.session;
    const age =
        hoursToMilliseconds(config.session.ttlHours) || hoursToMilliseconds(48);
    const KnexSessionStore = knexSessionStore(session);
    Iif (db) {
        store = new KnexSessionStore({
            tablename: 'unleash_session',
            createtable: false,
            // @ts-ignore
            knex,
        });
    } else {
        store = new session.MemoryStore();
    }
    return session({
        name: 'unleash-session',
        rolling: false,
        resave: false,
        saveUninitialized: false,
        store,
        secret: [config.server.secret],
        cookie: {
            path:
                config.server.baseUriPath === ''
                    ? '/'
                    : config.server.baseUriPath,
            secure: config.secureHeaders,
            maxAge: age,
        },
    });
}
 
export default sessionDb;