Skip to content

Commit 4924bc6

Browse files
committed
Add helper function to safely extract content type from headers
1 parent 04667fa commit 4924bc6

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

lib/handlers/put.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
module.exports = handler
22

33
const debug = require('debug')('solid:put')
4+
const getContentType = require('../utils').getContentType
45

56
async function handler (req, res, next) {
67
const ldp = req.app.locals.ldp
78
debug(req.originalUrl)
89
res.header('MS-Author-Via', 'SPARQL')
910

1011
try {
11-
await ldp.put(req, req, req.headers['content-type'])
12+
await ldp.put(req, req, getContentType(req.headers))
1213
debug('succeded putting the file')
1314

1415
res.sendStatus(201)

lib/utils.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ module.exports.fullUrlForReq = fullUrlForReq
99
module.exports.routeResolvedFile = routeResolvedFile
1010
module.exports.getQuota = getQuota
1111
module.exports.overQuota = overQuota
12+
module.exports.getContentType = getContentType
1213

1314
const fs = require('fs')
1415
const path = require('path')
@@ -222,3 +223,20 @@ function actualSize (root) {
222223
function _asyncReadfile (filename) {
223224
return util.promisify(fs.readFile)(filename, 'utf-8')
224225
}
226+
227+
/**
228+
* Get the content type from a headers object
229+
* @param headers An Express headers object
230+
* @return {string} A content type string
231+
*/
232+
function getContentType (headers) {
233+
const headerValue = headers['content-type']
234+
235+
// Default content type as stated by RFC 822
236+
if (!headerValue) {
237+
return 'text/plain'
238+
}
239+
240+
// Remove charset suffix
241+
return headerValue.split(';')[0]
242+
}

test/unit/utils-test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,18 @@ describe('Utility functions', function () {
7070
assert.equal(utils.fullUrlForReq(req), 'https://example.com/resource1?sort=desc')
7171
})
7272
})
73+
74+
describe('getContentType()', () => {
75+
it('should default to text/plain', () => {
76+
assert.equal(utils.getContentType({}), 'text/plain')
77+
})
78+
79+
it('should get a basic content type', () => {
80+
assert.equal(utils.getContentType({ 'content-type': 'text/html' }), 'text/html')
81+
})
82+
83+
it('should get a content type without its charset', () => {
84+
assert.equal(utils.getContentType({ 'content-type': 'text/html; charset=us-ascii' }), 'text/html')
85+
})
86+
})
7387
})

0 commit comments

Comments
 (0)