Skip to content

Commit

Permalink
feat: add pop method
Browse files Browse the repository at this point in the history
  • Loading branch information
igorissen committed Feb 1, 2024
1 parent b00cc51 commit 93c5728
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,18 @@ internals.Yar = class {
return value === undefined ? null : value;
}

pop(key) {
const value = this._store[key];

if (!value) {
return null;
}

this.clear(key);

return value;
}

set(key, value) {

Hoek.assert(key, 'Missing key');
Expand Down
61 changes: 61 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1527,4 +1527,65 @@ describe('yar', () => {
expect(res2.result.nomsg).to.exist();
});
});

describe('pop(key)', () => {
it('gets value from session and removes it', async () => {

const server = new Hapi.Server();

server.route([
{
method: 'GET', path: '/1', handler: (request, h) => {

const returnValue = request.yar.set({
some: '2',
and: 'thensome'
});
expect(returnValue.some).to.equal('2');
expect(returnValue.and).to.equal('thensome');
return '1';
}
},
{
method: 'GET', path: '/2', handler: (request, h) => {

const some = request.yar.pop('some');
return some;
}
},
{
method: 'GET', path: '/3', handler: (request, h) => {

const some = request.yar.pop('some');
return some || '3';
}
}
]);

await server.register({
plugin: Yar, options: {
maxCookieSize: 0,
cookieOptions: {
password: internals.password,
isSecure: false
}
}
});

await server.start();

const res = await server.inject({ method: 'GET', url: '/1' });
expect(res.result).to.equal('1');
const header = res.headers['set-cookie'];
const cookie = header[0].match(internals.sessionRegex);

const res2 = await server.inject({ method: 'GET', url: '/2', headers: { cookie: cookie[1] } });
expect(res2.result).to.equal('2');
const header2 = res2.headers['set-cookie'];
const cookie2 = header2[0].match(internals.sessionRegex);

const res3 = await server.inject({ method: 'GET', url: '/3', headers: { cookie: cookie2[1] } });
expect(res3.result).to.equal('3');
});
});
});

0 comments on commit 93c5728

Please sign in to comment.