Skip to content

Instantly share code, notes, and snippets.

@JesterXL
Created August 31, 2021 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JesterXL/7854101d60c0e628b45f577c55cff382 to your computer and use it in GitHub Desktop.
Save JesterXL/7854101d60c0e628b45f577c55cff382 to your computer and use it in GitHub Desktop.
const binaryBody = await res.buffer()
const body = binaryBody.toString('binary')
debug("first 255 of string body: %s", body.substr(0, 255))
const { isAnError, parsedResult } = verifyNotJSONErrorMessage(body)
debug("isAnError: %o", isAnError)
if(isAnError) {
return failure({ isAnError, parsedResult })
}
const boundaryHeader = res.headers.get('content-type')
debug("boundaryHeader: %s", boundaryHeader)
if(isNil(boundaryHeader) || (isString(boundaryHeader) && boundaryHeader.indexOf('boundary=') === -1)) {
return failure(new Error('Failed to find valid boundary header, no way to know how to parse the multipart response without it.'))
}
const boundary = boundaryHeader.split('boundary=')[1]
const {ok, data, error} = parseMultipartMixed('--' + boundary, body)
debug("ok:", ok)
debug("error: %o", error)
const parseMultipartMixed = (boundary, body) => {
try {
debug("parseMultipartMixed, boundary:", boundary)
const splitted = body.split(boundary)
// console.log("splitted:", splitted)
const isBlank = o =>
o === ''
|| o === '\n'
|| o === '\n\r'
|| o === '\r'
const notBlank = negate(isBlank)
const isEnding = o =>
o === '--\n'
|| o === '--'
|| o === '--\r'
const notEnding = negate(isEnding)
const notBlankNorEnding = o => notBlank(o) && notEnding(o)
const cleaned = map(i => {
if(isBlank(i) || isEnding(i)) {
return {keep: false, data: i}
} else {
return {keep: true, data: i}
}
}, splitted)
const filtered = filter(i => i.keep, cleaned)
const rawFilter = map(i => i.data, filtered)
const trimmedRaw = map(i => i.trim(), rawFilter)
const KNOWN_CONTENT_TYPES = [
'application/pdf',
'image/tiff',
'application/json'
]
const containsKnownContentType = o =>
some(
type => o.indexOf(type) > -1,
KNOWN_CONTENT_TYPES
)
const findMatchingContentType = string =>
find(
knownType => string.indexOf(knownType) > -1,
KNOWN_CONTENT_TYPES,
)
const filteredKnownContentTypes = filter(containsKnownContentType, trimmedRaw)
const mappedKnownContentTypes = map(
i => ({
contentType: findMatchingContentType(i),
data: i
}),
filteredKnownContentTypes
)
// log("mappedKnownContentTypes:", mappedKnownContentTypes)
const splitFilterTypes = map(
i => ({...i, data: last(i.data.split(`Content-Type: ${i.contentType}`)).trim()}),
mappedKnownContentTypes
)
// log("splitFilterTypes:", splitFilterTypes)
return {ok: true, data: splitFilterTypes}
} catch(error) {
return {ok: false, error}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment