Skip to content

Instantly share code, notes, and snippets.

@elvis-onobo
Created November 19, 2020 10:08
Show Gist options
  • Save elvis-onobo/38e6cfef0bd15f8d4d4e59a3cd348b88 to your computer and use it in GitHub Desktop.
Save elvis-onobo/38e6cfef0bd15f8d4d4e59a3cd348b88 to your computer and use it in GitHub Desktop.
Database Transaction with Express Js and Objection.js
"use strict";
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const randomstring = require("randomstring");
const nodemailer = require("nodemailer");
const env = require("dotenv").config();
const mailgun = require("mailgun-js");
const credentials = {
apiKey: process.env.AFRICASTALKING_API_KEY, // use your sandbox app API key for development in the test environment
username: process.env.AFRICASTALKING_USERNAME, // use 'sandbox' for development in the test environment
};
const AfricasTalking = require("africastalking")(credentials);
const User = require("../../models/User");
const Ussd = require("../../models/Ussd");
// const errorHandler = require('../../handler/ObjectionErrorHandler')
const sms = AfricasTalking.SMS;
/**
* REGISTRATION FLOW
* 1. User registers with phone number and other data
* 2. A verification code is sent to user via text after being stored in DB
* 3. User submits the code on the verification page to ve verified
*/
exports.registerUser = async (req, res) => {
try {
const { firstname, lastname, phone, email, password } = req.body;
const key = randomstring.generate({
length: 6,
charset: "alphanumeric",
});
const ussd = Math.floor(Math.random() * 10000 + 99);
const trxResult = await User.transaction(async (trx) => {
// this is the first operation
const userData = await User.query(trx).insert({
firstname,
lastname,
phone,
email,
password: await bcrypt.hash(password, 10),
key,
});
// if the operation fails here, everything will be rolled back
// because it is wrapped in a transaction
// this is the second operation
const ussdData = await Ussd.query(trx).insert({
user_id: userData.id,
ussd,
});
return userData;
});
const token = jwt.sign(
{ user: trxResult },
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn: process.env.JWT_EXP,
}
);
// Send verification code via SMS
try {
const options = {
to: [trxResult.phone],
message: `Welcome ${trxResult.firstname}, use
the following code to complete your registration: ${trxResult.key}`,
};
const smsRes = await sms.send(options);
if (smsRes.SMSMessageData.Recipients[0].status == "Success") {
res.status(201).json({
status: "success",
message: "You have been registered",
token,
});
}
} catch (error) {
res.json({
status: "failed",
message: "Your registration did not complete properly.",
});
}
} catch (errorCreatingUser) {
res.status(400).json({
status: "failed",
message: errorCreatingUser.message,
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment