Skip to content

Commit

Permalink
Refactor code and add slug to form data
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcrammer committed Jan 4, 2024
1 parent 49e10b2 commit ca1e2b4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/config/CodedError.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class CodedError extends Error {
constructor(message, code, data) {
super(message) // Human-readable message
this.name = this.constructor.name
this.name = this.constructor?.name || "Unnamed Error"
this.code = code // Machine-readable details
this.data = data
}
Expand Down
12 changes: 10 additions & 2 deletions src/routes/purchase.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import checkProrated from "../utils/checkProrated"
const router = express.Router()

router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (req, res) => {
const { product_id, email, phone, card_token, exp_month, exp_year, cardholder_name, api_token, whitelabel } = req.body
const { product_id, email, phone, card_token, exp_month, exp_year, cardholder_name, api_token, whitelabel, slug } =
req.body

try {
if (!product_id) throw new CodedError("product_id is required", "PUR01")
Expand Down Expand Up @@ -88,7 +89,14 @@ router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (
}
}

const formData = convertToFormata({ email, phone, active: 0, name: cardholder_name, whitelabel_id: whitelabelID })
const formData = convertToFormata({
email,
phone,
active: 0,
name: cardholder_name,
whitelabel_id: whitelabelID,
slug,
})
const newUserRequest = await fetch(process.env.API_URL + "/users", {
method: "POST",
headers: {
Expand Down
26 changes: 22 additions & 4 deletions src/utils/convertToFormdata.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
import FormData from "form-data"
import CodedError from "../config/CodedError"

export default function convertToFormata(json) {
const formData = new FormData()
try {
const formData = new FormData()

console.log(json)

const append = (key, value) => {
const keyIsUndefined = typeof value === "undefined"
const valueIsUndefined = typeof value === "undefined"
const valueIsNull = value === null || value === "null"

if (keyIsUndefined || valueIsUndefined || valueIsNull) return

for (const key in json) {
if (typeof key !== "undefined" && typeof json?.[key] !== "undefined") {
formData.append(key, json?.[key])
}

for (const key in json) {
console.log("key", key)
console.log("value", json?.[key])

append(key, json?.[key])
}
return formData
} catch (error) {
throw new CodedError(error, "CON1")
}
return formData
}

0 comments on commit ca1e2b4

Please sign in to comment.