John Carlo
John Carlo

Reputation: 54

Adding data with auto-generated fields with Sequelize.js

I want to create a row in my payouts table which has a auto-generated code upon creation.

On my postman, this is my input on my Body:

{
    "partner_id": 1,
    "user_id": 913,
    "earnings": "3348.93",
    "process_by": 21,
    "receipt": "asdasds",
    "message": "",
    "data": "{\"mop\":\"-deposit\"}"
}

and this is the return Json data:

{
 "created_at": "2020-01-08T02:51:29.711Z",
 "updated_at": "2020-01-08T02:51:29.711Z",
 "id": 7,
 "partner_id": 1,
 "user_id": 913,
 "earnings": "3348.93",
 "process_by": 21,
 "receipt": "asdasds",
 "message": "",
 "data": "{\"mop\":\"-deposit\"}",
 "updatedAt": "2020-01-08T02:51:32.250Z"
}

it outputs the body, but except for the code.

Here is the createCode function on my PartnerPayoutsRepository.js

createCode(length, code) {
var code = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
  code += characters.charAt(Math.floor(Math.random() * charactersLength));
}

 return code;
}

and this is my post api:

 router.post('/', isAdmin, validator, async (req, res) => {
 try {
   const data = req.params.code;
   const code = await PartnersPayoutRepository.createCode(data);
   const partner_payout = await PartnersPayoutRepository.create(req.body,code);
   res.json(partner_payout);
 } catch (error) {
   console.log(error);
   res.sendStatus(500);
  }
});

Any ideas why and how to deal with this? Thanks.

Upvotes: 0

Views: 308

Answers (2)

John Carlo
John Carlo

Reputation: 54

I have solved this problem by adding length on my post api and reconstructing the function.

router.post('/', addPartnerTransactionRules(), validator, async (req, res) => {
try {
  const length = 8;
  const code = PartnersTransactionRepository.createCode(length,req.body.code);
  const insertData = req.body;
  insertData.code = code;
  insertData.user_id = req.user.id;
  const create_code = await PartnersTransactionRepository.create(insertData);
  res.json(create_code);
} catch (error) {
  console.log(error);
  res.sendStatus(500);
  }
 }
);

Upvotes: 0

shiva2492
shiva2492

Reputation: 429

Here is the doc for inserting a row using sequelize https://sequelize.org/master/class/lib/model.js~Model.html#static-method-create, it takes two arguments first is the data of type object second is options for insertion which is also of type object. Your create sends code in second object.

post_api.js

 router.post('/', isAdmin, validator, async (req, res) => {
 try {
   const data = req.params.code;
   const code = await PartnersPayoutRepository.createCode(data);

   **// add code to the req.body object**
   req.body.code = code

   const partner_payout = await PartnersPayoutRepository.create(req.body);
   res.json(partner_payout);
 } catch (error) {
   console.log(error);
   res.sendStatus(500);
  }
});

Upvotes: 1

Related Questions