Skip to content

Instantly share code, notes, and snippets.

@dumebi
Created March 28, 2021 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dumebi/feb785fb02df9c55a050f884afcfe68f to your computer and use it in GitHub Desktop.
Save dumebi/feb785fb02df9c55a050f884afcfe68f to your computer and use it in GitHub Desktop.
example structure
const mongoose = require('mongoose');
const utils = require("./utils");
const RabbitMQ = require('./rabbitmq')
const subscriber = require('./rabbitmq')
require('dotenv').config();
// Socket config
module.exports = {
mongo() {
mongoose.promise = global.promise;
mongoose
.connect(utils.config.mongo, {
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500
})
.then(() => {
console.log('MongoDB is connected')
})
.catch((err) => {
console.log(err)
console.log('MongoDB connection unsuccessful, retry after 5 seconds.')
setTimeout(this.mongo, 5000)
})
},
async rabbitmq() {
RabbitMQ.init(utils.config.amqp_url);
},
async subscribe() {
await subscriber.init(utils.config.amqp_url);
},
}
const NotifmeSdk = require('notifme-sdk').default
const notifmeSdk = new NotifmeSdk({
channels: {
email: {
// If "Provider1" fails, use "Provider2"
multiProviderStrategy: 'fallback',
providers: [{
type: 'smtp',
host: "smtp.gmail.com",
port: 465,
service: "Gmail",
secure: true,
auth: {
user: `${process.env.MAIL_USER}`,
pass: `${process.env.MAIL_PASS}`,
}
}, {
type: 'sendgrid',
apiKey: `${process.env.SENDGRID_KEY}`
}]
},
sms: {
// Use "Provider1" and "Provider2" in turns (and fallback if error)
// multiProviderStrategy: 'roundrobin',
providers: [{
type: 'twilio',
accountSid: `${process.env.TWILIO_SID}`,
authToken: `${process.env.TWILIO_AUTH}`
}]
},
voice: {
providers: [{
type: 'twilio',
accountSid: `${process.env.TWILIO_SID}`,
authToken: `${process.env.TWILIO_AUTH}`
}]
},
push: {
providers: [{
type: 'fcm',
id: `${process.env.FCM_APP_ID}`
}]
}
}
})
exports.sendMail = async (format, data) => {
if (!format || !data.to || !data) {
HandleError("Not all parameters were sent");
}
const message = {
from: "GetEquity HQ <hello@getequity.io>",
to: data.to,
subject: data.subject,
html: format,
};
return notifmeSdk.send({ email: message });
};
exports.sendText = async (format, data) => {
if (!format || !data.to || !data) {
HandleError("Not all parameters were sent");
}
const message = {
from: "",
to: data.to,
text: "",
};
if (data.channel == "wa") {
message.to = `whatsapp:${data.to}`;
message.from = `whatsapp:${from}`;
}
return notifmeSdk.send({ sms: message })
};
exports.sendPush = async (format, data) => {
if (!format || !to || !data) {
HandleError("Not all parameters were sent");
}
let action;
const message = {
registrationToken: data.deviceID,
title: '',
body: '',
};
return notifmeSdk.send({ push: message })
};
function HandleError(error) {
throw new Error(error);
}
exports.handleSuccess = (res, code, data, message) => res.status(parseInt(code, 10)).json({
status: "success",
message,
data,
});
const express = require('express')
const MessageController = require('../http/controllers/message')
const { validateChannelParams, validateAddAddress, validatePhone, validateChannelandAddressIdParams, validateChannelandMessageIdParams, handleMessages, validateMessageID, validateMessageQuery } = require('../http/validation/message')
const { methodNotAllowedHandler } = require('../helpers/utils')
const router = express.Router()
/**
* Message Routes
*/
router.route('/:channel/addresses/').post(validateChannelParams, validatePhone, validateAddAddress, MessageController.createAddress).get(validateChannelParams, MessageController.getAddresses).all(methodNotAllowedHandler)
router.route('/:channel/incoming/').post(validateChannelParams, MessageController.incoming).all(methodNotAllowedHandler)
router.route('/:channel/incoming-status/:mid').post(validateChannelandMessageIdParams, MessageController.incomingStatus).all(methodNotAllowedHandler)
router.route('/:channel/addresses/:aid').get(validateChannelandAddressIdParams, MessageController.getAddress).delete(validateChannelandAddressIdParams, MessageController.deleteAddress).all(methodNotAllowedHandler)
// router.route('/:channel/addresses/:aid/incoming').get(validateChannelandAddressIdParams, MessageController.getIncomingMessages).all(methodNotAllowedHandler)
router.route('/:channel/addresses/:aid/messages').get(validateChannelandAddressIdParams, validateMessageQuery, MessageController.getMessages).post(validateChannelandAddressIdParams, handleMessages, MessageController.sendMessage).all(methodNotAllowedHandler)
router.route('/:channel/addresses/:aid/messages/:mid').get(validateChannelandAddressIdParams, validateMessageID, MessageController.getMessage).all(methodNotAllowedHandler)
//https://www.twilio.com/docs/sms/api/message-resource
module.exports = router
// Package Dependencies
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const compression = require('compression');
const flash = require('connect-flash');
const { handleError } = require('./utils/utils')
const app = express();
require('dotenv').config();
require('./utils/connection').mongo();
require('./utils/connection').rabbitmq();
require('./utils/connection').subscribe();
// require('./utils/connection').socket();
// redis-server --maxmemory 10mb --maxmemory-policy allkeys-lru
// Midelware stack
app.use(cors({
origin: '*'
}))
app.use(compression())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(logRequest);
app.use(express.static(path.join(__dirname, 'node_modules')))
app.use(express.static(path.join(__dirname, 'build/contracts')))
/* Application Routes */
app.use('/v1/', require('./routes'));
// catch 404 and forward to error handler
app.use((req, res) => {
handleError(req, res, 404, 'Page not found')
});
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment