Skip to content

Commit

Permalink
feat(wobe): add get cookie function on context (#33)
Browse files Browse the repository at this point in the history
* feat(wobe): add get cookie function in context to get a cookie in request headers

* feat: add test for single cookie
  • Loading branch information
coratgerl authored Jul 24, 2024
1 parent 3ee5879 commit 061b511
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/wobe/src/Context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,30 @@ describe('Context', () => {
)
expect(context.res.status).toEqual(301)
})

it('should get the cookie in the request headers', () => {
const request = new Request('https://example.com', {
headers: {
cookie: 'test=tata; test2=titi',
},
})
const context = new Context(request)

expect(context.getCookie('test')).toEqual('tata')
expect(context.getCookie('test2')).toEqual('titi')
expect(context.getCookie('invalid')).toBeUndefined()
})

it('should get the cookie in the request headers with only one cookie', () => {
const request = new Request('https://example.com', {
headers: {
cookie: 'test=tata',
},
})
const context = new Context(request)

expect(context.getCookie('test')).toEqual('tata')
expect(context.getCookie('test2')).toBeUndefined()
expect(context.getCookie('invalid')).toBeUndefined()
})
})
18 changes: 18 additions & 0 deletions packages/wobe/src/Context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,22 @@ export class Context {

return this.res.response || new Response(null, { status: 404 })
}

getCookie(name: string) {
const cookieHeader = this.request.headers.get('cookie')

if (!cookieHeader) return undefined

const split = cookieHeader
.split(';')
.map((cookie) => cookie.replaceAll(' ', ''))

const existingCookie = split.find(
(element) => element.split('=')[0] === name,
)

if (!existingCookie) return undefined

return existingCookie.split('=')[1]
}
}

0 comments on commit 061b511

Please sign in to comment.