Skip to content

Commit

Permalink
Fix set-data validation to support both json and multipart form data
Browse files Browse the repository at this point in the history
  • Loading branch information
vixhnuchandran committed Jun 6, 2024
1 parent c225d12 commit 78dbafc
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
19 changes: 12 additions & 7 deletions src/routes/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,19 @@ export const setData = async (req: Request, res: Response) => {
} else {
data = req.body.data
}
if (!data) console.log("no data")
const isMultipart: string | boolean = req.is("multipart/form-data")

const validationResult = validateSetDataReq({
dataset,
id,
name,
data,
isReplace,
})
const validationResult = validateSetDataReq(
{
dataset,
id,
name,
data,
isReplace,
},
isMultipart
)

if (!validationResult.isValid) {
console.error(validationResult.message)
Expand Down
36 changes: 34 additions & 2 deletions src/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,66 @@ export interface ValidationResult {
message?: string
}

export const validateSetDataReq = (obj: any): ValidationResult => {
export const validateSetDataReq = (
obj: any,
isMultipart: string | boolean
): ValidationResult => {
// Check for 'data' based on content type
if (isMultipart) {
if (!obj.file && (!obj.data || obj.data === "null")) {
return {
isValid: false,
message: "Invalid or missing 'data' in multipart form data.",
}
}
} else {
if (!obj.data) {
return {
isValid: false,
message: "Invalid or missing 'data' in JSON body.",
}
}
}

// Validate 'dataset'
if (!obj.dataset || typeof obj.dataset !== "string") {
return {
isValid: false,
message: "Invalid or missing 'dataset'. Must be a non-empty string.",
}
}

// Validate 'id'
if (!obj.id || typeof obj.id !== "string") {
return {
isValid: false,
message: "Invalid or missing 'id'. Must be a non-empty string.",
}
}

// Validate 'name'
if (!obj.name || typeof obj.name !== "string") {
return {
isValid: false,
message: "Invalid or missing 'name'. Must be a non-empty string.",
}
}

if (typeof obj.isReplace !== "boolean") {
// Validate 'isReplace'
const isReplace =
obj.isReplace === "true"
? true
: obj.isReplace === "false"
? false
: obj.isReplace
if (typeof isReplace !== "boolean") {
return {
isValid: false,
message:
"Invalid or missing 'replace'. Must be either 'true' or 'false'.",
}
}

return { isValid: true }
}

Expand Down

0 comments on commit 78dbafc

Please sign in to comment.