Skip to content

Commit

Permalink
Refactor the parser
Browse files Browse the repository at this point in the history
  • Loading branch information
EpeusJS committed Jul 4, 2024
1 parent eb5af42 commit e009499
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 12 deletions.
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@trojs/formdata-parser",
"version": "0.1.1",
"version": "0.1.2",
"description": "Parse the form data",
"type": "module",
"main": "src/form-data.js",
Expand Down Expand Up @@ -53,4 +53,4 @@
"globals": "^15.8.0",
"jscpd": "^4.0.5"
}
}
}
55 changes: 51 additions & 4 deletions src/form-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,53 @@
* @typedef {import('./types.d.ts').FormData} FormData
*/

/**
* @param {string} file
* @returns {string}
*/
const getFileName = (file) => {
const fileName = file.split(`filename="`)
if (fileName.length > 1) {
return fileName[1].split(`"\r\n`)[0]
}
throw new Error('No file name')
}

/**
* @param {string} file
* @returns {string}
*/
const getFileData = (file) => {
const fileData = file.split(`\r\n\r\n`)
if (fileData.length > 1) {
return fileData[1].split(`\r\n`)[0]
}
throw new Error('No file data')
}

/**
* @param {string} file
* @returns {string}
*/
const getField = (file) => {
const fieldName = file.split(`name="`)
if (fieldName.length > 1) {
return fieldName[1].split(`";`)[0]
}
throw new Error('No field')
}
/**
* @param {string} file
* @returns {string}
*/
const getContentType = (file) => {
const contentType = file.split(`Content-Type: `)
if (contentType.length > 1) {
return contentType[1].split(`\r\n`)[0]
}
throw new Error('No content type')
}

/**
* Parse multipart/form-data
* @param {string} data
Expand All @@ -21,10 +68,10 @@ export default (data, header) => {
return undefined
}
return {
fileName: file.split(`filename="`)[1].split(`"\r\n`)[0],
fileData: file.split(`\r\n\r\n`)[1].split(`\r\n`)[0],
field: file.split(`name="`)[1].split(`";`)[0],
contentType: file.split(`Content-Type: `)[1].split(`\r\n`)[0],
fileName: getFileName(file),
fileData: getFileData(file),
field: getField(file),
contentType: getContentType(file),
boundary
}
}).filter(file => file !== undefined)
Expand Down

0 comments on commit e009499

Please sign in to comment.