Skip to content

Commit

Permalink
feat(response): added support to Uint8Array
Browse files Browse the repository at this point in the history
  • Loading branch information
H4ad committed Jul 22, 2022
1 parent 8cbeb30 commit aa1b321
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
46 changes: 45 additions & 1 deletion __tests__/integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const {
makeResponse,
EACH_MATRIX
} = require('../jest-helpers')

const stream = require('stream')
const jestHelpersPath = path.join(__dirname, '..', 'jest-helpers')

let app, router, serverlessExpressInstance
Expand Down Expand Up @@ -103,6 +103,50 @@ describe.each(EACH_MATRIX)('%s:%s: integration tests', (eventSourceName, framewo
expect(response).toEqual(expectedResponse)
})

test('GET Uint8Array', async () => {
const multiValueQueryStringParameters = {
singleNormal: ['1']
}
const queryStringParameters = {
singleNormal: '1'
}
router.get('/uint8', (req, res) => {
const { singleNormal } = req.query
res.set('X-Custom-Header', singleNormal)

const readStream = new stream.PassThrough()
const buffer = Uint8Array.from(
Array.from('Hello serverless!').map(ch => ch.charCodeAt(0))
)

res.set('content-length', Buffer.byteLength(buffer))
res.set('content-type', 'application/octet-stream')

readStream.end(buffer)

readStream.pipe(res)
})
const event = makeEvent({
eventSourceName,
path: '/uint8',
httpMethod: 'GET',
queryStringParameters,
multiValueQueryStringParameters
})
const response = await serverlessExpressInstance(event)
const expectedResponse = makeResponse({
eventSourceName,
body: 'Hello serverless!',
headers: undefined,
multiValueHeaders: {
'content-type': ['application/octet-stream'],
'content-length': ['17'],
'x-custom-header': ['1']
}
})
expect(response).toEqual(expectedResponse)
})

test('resolutionMode = CALLBACK', (done) => {
const jsonResponse = { data: { name: 'Brett' } }
router.get('/users', (req, res) => {
Expand Down
4 changes: 3 additions & 1 deletion src/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ function getString (data) {
return data.toString('utf8')
} else if (typeof data === 'string') {
return data
} else if (data instanceof Uint8Array) {
return new TextDecoder().decode(data)
} else {
throw new Error(`response.write() of unexpected type: ${typeof data}`)
}
}

function addData (stream, data) {
if (Buffer.isBuffer(data) || typeof data === 'string') {
if (Buffer.isBuffer(data) || typeof data === 'string' || data instanceof Uint8Array) {
stream[BODY].push(Buffer.from(data))
} else {
throw new Error(`response.write() of unexpected type: ${typeof data}`)
Expand Down

0 comments on commit aa1b321

Please sign in to comment.