UNPKG

@kikiutils/nitro-session

Version:
50 lines (47 loc) 1.75 kB
import { getRequestIP } from 'h3'; import { CookieOrHeaderDataHandler } from './cookie-or-header.mjs'; import { UnstorageDataHandler } from './unstorage.mjs'; class DataHandler { #handler; #maxAgeMilliseconds; #strictIpValidation; constructor(handler, maxAge, strictIpValidation) { this.#handler = handler; this.#maxAgeMilliseconds = maxAge * 1000; this.#strictIpValidation = strictIpValidation; } #getRequestIp(event) { return getRequestIP(event, { xForwardedFor: true }) || getRequestIP(event); } static async createInstance(options) { let handler; if (options.storage?.data?.driver === 'cookie/header') { handler = new CookieOrHeaderDataHandler(options.storage.data.options); } else handler = await UnstorageDataHandler.createInstance(options.storage?.data || { driver: 'memory' }); return new this(handler, options.maxAge ?? 86400, !!options.strictIpValidation); } async delete(token) { await this.#handler.delete(token); } async get(event, token) { const data = await this.#handler.get(event, token); if (data && data[0] + this.#maxAgeMilliseconds >= Date.now()) { if (this.#strictIpValidation && this.#getRequestIp(event) !== data[2]) return; return data[1]; } } async setAndGetToken(event, data) { const toSetData = [ Date.now(), data, ]; if (this.#strictIpValidation) toSetData.push(this.#getRequestIp(event)); return await this.#handler.setOrProcessAndGetToken(event, toSetData); } } export { DataHandler }; //# sourceMappingURL=index.mjs.map