Skip to content

Commit

Permalink
feat(cookies): Add cookie support #3 - Only for Cookie Store API supp…
Browse files Browse the repository at this point in the history
…orting browsers
  • Loading branch information
jjak0b committed Mar 22, 2021
1 parent 5ee77d5 commit 9f6cba8
Showing 1 changed file with 50 additions and 14 deletions.
64 changes: 50 additions & 14 deletions src/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const charset = require('charset');
const jschardet = require('jschardet');
const Buffer = require("buffer").Buffer;
const debug = require( "debug" )('express-service');
const { fromJSON: cookieFromJSON } = require("tough-cookie");

// ServiceWorker script
// functions as an adaptor between the Express
Expand Down Expand Up @@ -113,8 +114,8 @@ class Server {
*/
function buildRequest( request ) {
return request.blob()
.then(( blob ) => blob.text()
.then( ( body ) => {
.then( blob => blob.text()
.then( body => new Promise( (resolve) => {

if (!request.body) {
// all browsers don't support Request.body: why ?!
Expand Down Expand Up @@ -144,21 +145,56 @@ function buildRequest( request ) {
headers.append("content-length", Buffer.byteLength(body, encoding).toString())
}

Object.defineProperty(request, 'headers', { value: headers })

let req = new http.IncomingMessage(null, request, 'fetch', 6000)
getCookiesForRequest( request )
.then( (cookies) => {
if (cookies && cookies.length && !headers.has("Cookie" ) ) {
for (let cookie of cookies) {
headers.append( "Cookie", cookie.toString() );
}
}
})
.finally( () => {
Object.defineProperty(request, 'headers', { value: headers })

let req = new http.IncomingMessage(null, request, 'fetch', 6000)

// empty stubs
req.method = request.method
req.connection = {
encrypted: !!global.isSecureContext
}
req.socket = {} // this could be linked to a virtual socket

resolve( req );
})
}))
)
}

// empty stubs
req.method = request.method
req.connection = {
encrypted: !!global.isSecureContext
/**
*
* @param request {Request}
* @return {Promise<Cookie[]|null>}
*/
function getCookiesForRequest( request ) {
if( "cookieStore" in self ) {
return self.cookieStore.getAll( { url: self.location.href } )
.then( (cookiesStored) => {
if( cookiesStored ) {
// adapt Cookie Store API structure to "tough-cookie" object structure
return cookiesStored.map( (cookie) => {
cookie.key = cookie.name;
return cookieFromJSON( cookie );
});
}
req.socket = {} // this could be linked to a virtual socket

return req;
}))
return null;
})
.catch( () => Promise.resolve(null ) )
}
else {
return Promise.resolve( null );
}
}

/**
*
* @return {http.ServerResponse}
Expand Down

0 comments on commit 9f6cba8

Please sign in to comment.