Agenad job is not getting start again after nodejs (express) server restart - javascript

I am using node agenda while scheduling I am able to successfully save job and its running fine. But while restarting the server the previous jobs are not getting start again. Not sure why, I tried few solutions found online but unable to make it work.
Can anyone help me with this.
I am using Nodemon with node express.
I am creating schedule using API calls
Below is app.js file
'use strict';
require('dotenv').config();
const express = require('express');
const { initialize_mongodb_database_connection } = require('./helpers/mongodb_database');
const bodyParser = require('body-parser');
const Agenda = require('agenda');
const app = express();
let logger = require('logger');
let chalk = require('chalk');
let moment = require('moment');
let mongoose = require('mongoose');
const agenda = new Agenda({
db: {address: process.env.MONGODB_URI, collection: 'scheduled_reports'},
processEvery: '30 seconds'
});
app.use(bodyParser.json());
//
// Parse application/x-www-form-urlencoded
//
app.use(bodyParser.urlencoded({extended: false}));
app.use(require('./routes/v1/schedule_report/schedule_report_routes'));
initialize_mongodb_database_connection();
sequr_app(app, [dummy_routes], {
staticDir: true,
});
let gracefulExit = function() {
if (mongoose.connection.readyState === 0) {
return process.exit(0);
}
mongoose.connection.close(function() {
return agenda.stop(function() {
logger.info({});
logger.info(chalk.bold("---------------------[ Server stopped at %s Uptime: %s ]---------------------------"), moment().format("YYYY-MM-DD HH:mm:ss.SSS"), moment.duration(process.uptime() * 1000).humanize());
return process.exit(0);
});
});
};
process.on("SIGINT", gracefulExit).on("SIGTERM", gracefulExit);
And this is my agenda file where I am routing API calls to create schedule
const Agenda = require('agenda');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'xx-xx#gmail.com',
pass: 'xx-xx-xx'
}
});
var mailOptions = {
from: 'example#example.com',
to: 'Example#gmail.com',
subject: 'Sending Email using Node.js',
text: 'Agenda Test'
};
const agenda = new Agenda({
db: {address: process.env.MONGODB_URI, collection: 'agendaJobs'},
processEvery: '30 seconds'
});
agenda.start();
agenda.defaultConcurrency(5);
const scheduleReport = async(report_data) => {
// HERE SCHEDULING/CREATING AGENDA SCHEDULE
agenda.on('start', job => {
console.log('-------------------------------------STARTED-----------------------------------------------');
console.log('Job %s starting', job.attrs.name);
console.log('-------------------------------------------------------------------------------------------');
});
const {
report_name,
priority
} = report_data;
agenda.define(report_name, {priority: priority, concurrency: 10}, (job, done) => {
const dateNow = new Date();
const data = job.attrs.data;
// The job.attrs.data is stored in our MongoDB collection so that it can be used to run the jobs.
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
//const date = new Date.now();
console.log('Email sent: ' + info.response + dateNow);
console.log(`Job ${job.attrs.name} finished`);
}
},done());
});
// HERE CREATING SCHEUDLE
await createWeeklySchedule(report_data);
agenda.on('complete', job => {
console.log('---------------------------------------FINISHED---------------------------------------------');
console.log(`Job ${job.attrs.name} completed succesfully...`);
console.log('--------------------------------------------------------------------------------------------');
});
}
const createWeeklySchedule = async(data) => {
const {
report_name,
schedule_info,
scheduled_timezone,
time_cron
} = data;
const weeklyReport = agenda.create(report_name, {data: schedule_info});
await agenda.start();
await agenda.every(time_cron,report_name);
console.log('Job successfully saved');
}
module.exports = scheduleReport;
Also I am starting app with app.js as main

Related

Status Code 502 - Server Error - Node.js Express & MongoDB - Incomplete response received from application

I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};

CONNECTION SOCKET.IO

I've been stuck for a few days now with a socket.io problem, more precisely between server to client.
On the client side, (Angular) I can emit an event, the server can grab and execute all the logic, but after the server to the client it doesn't show signs of life.
I've already expressed all the events, I've reformulated all the settings as it says in the documentation and nothing works, can anyone see where I'm going wrong?
"socket.io": "^4.5.1"
"socket.io-client": "^4.5.1",
ANGULAR (CLIENT-SIDE)
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { io, Socket } from 'socket.io-client';
import { environment } from 'src/environments/environment';
#Injectable({
providedIn: 'root'
})
export class SocketIoService {
socket: Socket;
constructor() {}
connect(token: string, userName: string){
this.socket = io(environment.path.hermsUrl, {
query: {
token,
userName
}
});
}
disconnect(){
this.socket.disconnect();
}
sendMessage(msg: any) {
this.socket.emit('send-message', (msg));
}
getConversation(){
this.socket.on('update-conversation', (conversation)=> {
console.log('############################################');
});
}
}
NODE.JS (SERVER-SIDE)
require('dotenv').config();
require('./Helpers/init_mongodb');
const express = require('express');
const cors = require('cors');
const createError = require('http-errors');
const chatController = require('./Controllers/chat.controller');
const Chat = require('./Models/chat.model');
const app = express();
const httServer = require('http').createServer(app);
const { verifyAccessToken } = require('./Helpers/jwt_token');
const userRoute = require('./Routes/user.routes');
const eventRoute = require('./Routes/event.routes');
const chatRoute = require('./Routes/chat.routes');
const decode = require('jwt-decode');
const PORT = process.env.PORT || 5005;
const io = require('socket.io')(httServer, {
cors: {
origins: ["*"]
}
});
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use('/path/user', userRoute);
app.use('/path/event', eventRoute);
app.use('/path/chat', chatRoute);
app.use(async (req, res, next) => {
next(createError.NotFound('THIS ROUTE DOES NOT EXIST'))
});
app.get('/', verifyAccessToken, async (req, res, next) => {
res.send('HELLO THERE')
});
app.use((err, req, res, next) => {
res.status(err.status || 500)
res.send({
error: {
status: err.status || 500,
message: err.message,
},
})
});
io.on("connection", (socket) => {
const decodedObj = decode(socket.handshake.query.token);
socket.id = decodedObj.aud;
const userName = socket.handshake.query.userName;
console.log("========= SOCKET.IO CONNECTED =========");
console.log("");
console.log("USERNAME: " + userName);
console.log("ID: " + socket.id);
console.log("");
console.log("=======================================");
socket.on('send-message', async (message) => {
try{
const chatId = message.chatId;
const decodedObj = decode(message.sender);
const senderId = decodedObj.ID;
const userSocketId = message.userId;
const date = new Date();
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
const hour = date.getHours();
const minuts = date.getMinutes();
const sendingDate = day + "/" + month + "/" + year + " " + hour + ":" + minuts;
const newMsg = {
msgType: message.typeOfMsg,
message: message.msg,
date: sendingDate,
sender: senderId
}
const conversation = await Chat.findById(chatId);
if(!conversation){
throw createError.NotFound();
}
conversation.messages.push(newMsg);
const updateConversation = await Chat.findByIdAndUpdate(chatId, conversation);
if(!updateConversation){
throw createError.InternalServerError();
}
console.log("!!!!!!!!!!! SEND EMIT FROM SOCKET/SERVER !!!!!!!!!!!!!!!");
io.emit('update-conversation', 'FROM SERVER');
io.emit('update-conversation');
io.local.emit('update-conversation');
io.local.emit('update-conversation', 'FROM SERVER');
socket.emit('update-conversation', 'FROM SERVER');
socket.emit('update-conversation');
socket.broadcast('update-conversation', 'FROM SERVER');
console.log("!!!!!!!!!!! EMIT SENDED !!!!!!!!!!!!!!!");
} catch (error) {
console.log(error);
}
});
socket.on("disconnect", () => {
console.log("########### SOCKET.IO DISCONNECTED ###########");
console.log("");
console.log("USERNAME: " + userName);
console.log("ID: " + socket.id);
console.log("");
console.log("##############################################");
});
});
httServer.listen(PORT, () => {
console.log(`SERVER RUNNING ON PORT ${PORT}`);
})
It appears you aren't yet listening for the update-conversation message in the client. Thus, when the server sends it, you don't have any client code to actually receive it.
You need to register the listener this.socket.on('update-conversation', ...) on the client-side when you first create the socket.io connection. Then, it will be ready to receive that message whenever the server sends that message.

Cannot POST /api/sentiment

I'm testing the endpoint for /api/sentiment in postman and I'm not sure why I am getting the cannot POST error. I believe I'm passing the correct routes and the server is listening on port 8080. All the other endpoints run with no issue so I'm unsure what is causing the error here.
server.js file
const express = require("express");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://tami00:MEUxClWqUNbLz359#cluster0.gmvao.mongodb.net/test?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.use('/api/favourite', require('./app/routes/favourite.routes'));
app.use('/api/review', require('./app/routes/review.routes'));
app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));
// routes
// require(".app/routes/favourite.routes")(app);
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "creator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'creator' to roles collection");
});
new Role({
name: "watcher"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'watcher' to roles collection");
});
}
});
}
sentiment-analysis routes file
const express = require('express');
const router = express.Router();
const getSentiment = require('../sentiment-analysis/sentimentAnalysis')
router.post('/api/sentiment', (req, res) => {
const data = req.body.data
const sentiment = getSentiment(data)
return res.send({sentiment})
})
module.exports = router;
sentimentAnalysis.js file
const aposToLexForm = require("apos-to-lex-form");
const {WordTokenizer, SentimentAnalyzer, PorterStemmer} = require("natural");
const SpellCorrector = require("spelling-corrector");
const stopword = require("stopword");
const tokenizer = new WordTokenizer();
const spellCorrector = new SpellCorrector();
spellCorrector.loadDictionary();
const analyzer = new SentimentAnalyzer('English', PorterStemmer, 'afinn')
function getSentiment(text){
if(!text.trim()) {
return 0;
}
const lexed = aposToLexForm(text).toLowerCase().replace(/[^a-zA-Z\s]+/g, "");
const tokenized = tokenizer.tokenize(lexed)
const correctSpelling = tokenized.map((word) => spellCorrector.correct(word))
const stopWordsRemoved = stopword.removeStopwords(correctSpelling)
console.log(stopWordsRemoved)
const analyzed = analyzer.getSentiment(stopWordsRemoved);
console.log(analyzed)
}
module.exports = getSentiment;
console.log(getSentiment("Wow this is fantaztic!"))
console.log(getSentiment("let's go together?"))
console.log(getSentiment("this is so bad, I hate it, it sucks!"))
I see that you use your routes like: app.use('/api/sentiment', require('./app/routes/sentiment-analysis.routes'));. But then in your sentiment-analysis you again use /api/sentiment so your request URL should be /api/sentiment/api/sentiment
Shouldn't it be:
const data = req.body.data

Not able to send or receive messages on slack for a bot build using Microsoft Bot Framework

I am trying to build a slack bot using the Microsoft Bot framework. I have created a bot using bot channels registration and also running a local node.js server. I tested my bot in web chat and it works fine but not working in slack. As soon as a user adds the bot to his apps list he needs to get a message welcome, the welcome message appears in web chat but not in slack app.
//importing npm packages
const express = require('express')
const {
BotFrameworkAdapter,
MemoryStorage,
UserState
} = require('botbuilder')
const path = require("Path")
const {
WelcomeBot
} = require("./WelcomeBot")
const {
SlackAdapter
} = require('botbuilder-adapter-slack')
//environmental path variables file config
const ENV_FILE = path.join(__dirname, '.env')
require('dotenv').config({
path: ENV_FILE
})
//object creation
const app = express()
//An adapter object for botframeworkadapter
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
})
// const adapter = new SlackAdapter({
// clientSigningSecret: process.env.SLACK_SECRET,
// botToken: process.env.SLACK_TOKEN
// })
adapter.onTurnError = async(context, error) => {
console.error(`\n [onTurnError] unhandled error: ${error}`)
await context.sendTraceActivity('OnTurnError Trace', `${error}`, 'https://www.botframework.com/schemas/error', 'TurnError');
await context.sendActivity('The bot encountered an error or bug')
await context.sendActivity('To continue to run this bot, please fix the bot source code')
}
const memoryStorage = new MemoryStorage()
const userState = new UserState(memoryStorage)
const bot = new WelcomeBot(userState)
app.listen(process.env.port || process.env.PORT || 3000, function() {
console.log("listening....")
})
app.get("/api/messages", (req, res) => {
res.send("Connected")
})
app.post('/', (req, res) => {
console.log(req)
const {
challenge
} = req.body;
res.send({
challenge
});
})
app.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async(context) => {
await bot.run(context)
})
})
The above is my main server file and the next is a welcome function to welcome the user:
const {
ActionTypes,
ActivityHandler,
CardFactory,
MessageFactory
} = require('botbuilder')
const WELCOMED_USER = 'welcomedUserProperty'
const quick_reply1 = require("./User-inputs/Quick_replies")
const cardActions = [{
type: ActionTypes.PostBack,
title: 'List all the tasks',
value: 'List all the tasks',
imageAltText: 'R'
}]
myvalues = ['in progress', 'in review', 'blocked', 'Done']
class WelcomeBot extends ActivityHandler {
constructor(userState) {
super()
this.welcomedUserProperty = userState.createProperty(WELCOMED_USER)
this.userState = userState
this.onMessage(async(context, next) => {
const text = context.activity.text.toLowerCase()
switch (text) {
case "list all the tasks":
await context.sendActivity("Hello")
}
await next()
})
this.onMembersAdded(async(context, next) => {
var reply = MessageFactory.suggestedActions(cardActions, 'What can I do for you today?');
for (const idx in context.activity.membersAdded) {
if (context.activity.membersAdded[idx].id != context.activity.recipient.id) {
await context.sendActivity("Welcome to Jaas Slackbot")
await context.sendActivity(reply);
}
}
})
}
async run(context) {
await super.run(context)
await this.userState.saveChanges(context)
}
}
exports.WelcomeBot = WelcomeBot;
The bot gets added to the workspace and have also created a channel on bot registration channel azure but yet not working.

Mongoose saves data twice for one request

I'm relatively new with mongodb and express and I wish to save data which has been retrieved via an api call, to my database. For some reason my server saves the data twice (creates two documents with same details but different id's) for a single get request and I can't figure out why
const log = console.log;
const express = require('express')
const port = process.env.PORT || 8000
const movieServer = require('./movie-getter')
const { Movie } = require('./model/Movie')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/ConspireView', { useNewUrlParser: true});
const app = express()
app.get('/movie/:name/:year', (req, res) => {
const name = req.params.name
const year = req.params.year
// let movieObject
movieServer.getMovie(name, year).then((result) => {
new Movie({
name: result.title,
year: result.release_date,
poster: result.poster_path,
banner: result.backdrop_path,
numOfDiscussions: 0,
numOfComments: 0,
vote_average: 0
// discussions: null
}).save().then(result => {
res.send(result)
})
}).catch((error) => {
log(error)
})
})
Are there any syntactic errors here?

Categories