google cloud function error DEADLINE EXCEEDED - node.js

I'm trying to write a simple pub/sub triggered cloud function to update my Firestore collection of stocks.I'm getting a bunch of weird error messages with one prominent of Error: 4 DEADLINE_EXCEEDED: Deadline exceeded. Whats even more strange that some stocks gets updated correctly while others don't. Im new to Javascript/Typescript so obviously I have some misunderstanding about how to return promises in this case here. The idea here is very simple loop through each ticker in the collection make a request to updated data then update existing document data and save it
export const updateChart = functions.pubsub.schedule('35 16 * * 1-5').timeZone('America/New_York').onRun(async(_context) => {
const key = functions.config().services.key as string
const db = admin.firestore()
const charts5DRef = db.collection("charts5D")
var needsUpdate : boolean = true
// I cut off some unrelated code for brevity sake
if (needsUpdate){
const snapshot = await charts5DRef.get()
var path = ``
const timestamp = Date.now() / 1000
return snapshot.forEach(async function(document){ // this could contain 100's of stock tickers
const ticker = document.id
const docData = document.data()
var labels = docData.labels as [string]
var marketNotional = docData.marketNotional as [number]
var marketTrades = docData.marketNumberOfTrades as [number]
var dates = docData.dates as [string]
var closings = docData.close as [number]
var volume = docData.marketVolume as [number]
path = `apiUrl to get data`
const options = {
method : 'GET',
uri : path,
resolveWithFullResponse : true,
}
await req(options).then(async(response)=>{
if(response.statusCode === 200){
const resultData = JSON.parse(response.body)
const updatedPrices = resultData as [IntradayPrice]
updatedPrices.forEach(function(value){
if(value.close !== undefined){
closings.splice(0,1)
marketTrades.splice(0,1)
marketNotional.splice(0,1)
labels.splice(0,1)
dates.splice(0,1)
volume.splice(0,1)
closings.push(value.close)
dates.push(value.date)
if(value.label !== undefined){ labels.push(value.label) } else { labels.push("") }
if(value.marketNotional !== undefined) { marketNotional.push(value.marketNotional) } else { marketNotional.push(0) }
if(value.marketNumberOfTrades !== undefined) { marketTrades.push(value.marketNumberOfTrades) } else { marketTrades.push(0) }
if(value.marketVolume !== undefined) { volume.push(value.marketVolume) } else { volume.push(0) }
}
})
await charts5DRef.doc(ticker).set({lastUpdate : timestamp,close : closings, labels : labels, marketVolume : volume,marketNumberOfTrades : marketTrades, marketNotional : marketNotional, dates : dates}).then(()=>{
console.log(`Updated ${ticker} 5Dchart successfully`)
}).catch((error)=>{
console.log(error)
})
}
}).catch((error)=>{
console.log(error)
})
})
}else{
console.log("Markets closed")
return
}
})

ok so this solved the errors
export const updateChart = functions.pubsub.schedule('35 16 * * 1-5').timeZone('America/New_York').onRun(async(_context) => {
const key = functions.config().services.key as string
const db = admin.firestore()
const charts5DRef = db.collection("charts5D")
var needsUpdate : boolean = false
if (needsUpdate){
const snapshot = await charts5DRef.get()
var path = ``
const timestamp = Date.now() / 1000
const promises : bird<void>[] = []
snapshot.forEach(async function(document){
const ticker = document.id
const docData = document.data()
var labels = docData.labels as [string]
var marketNotional = docData.marketNotional as [number]
var marketTrades = docData.marketNumberOfTrades as [number]
var dates = docData.dates as [string]
var closings = docData.close as [number]
var volume = docData.marketVolume as [number]
path = `https://cloud.iexapis.com/stable/stock/${ticker}/intraday-prices?token=${key}&chartInterval=10`
const options = {
method : 'GET',
uri : path,
resolveWithFullResponse : true,
}
const promise = req(options).then(async(response)=>{
if(response.statusCode === 200){
const resultData = JSON.parse(response.body)
const updatedPrices = resultData as [IntradayPrice]
updatedPrices.forEach(function(value){
if(value.close !== undefined){
closings.splice(0,1)
marketTrades.splice(0,1)
marketNotional.splice(0,1)
labels.splice(0,1)
dates.splice(0,1)
volume.splice(0,1)
closings.push(value.close)
dates.push(value.date)
if(value.label !== undefined){ labels.push(value.label) } else { labels.push("") }
if(value.marketNotional !== undefined) { marketNotional.push(value.marketNotional) } else { marketNotional.push(0) }
if(value.marketNumberOfTrades !== undefined) { marketTrades.push(value.marketNumberOfTrades) } else { marketTrades.push(0) }
if(value.marketVolume !== undefined) { volume.push(value.marketVolume) } else { volume.push(0) }
}
})
await charts5DRef.doc(ticker).set({lastUpdate : timestamp,close : closings, labels : labels, marketVolume : volume,marketNumberOfTrades : marketTrades, marketNotional : marketNotional, dates : dates}).then(()=>{
console.log(`Updated ${ticker} 5Dchart successfully`)
}).catch((error)=>{
console.log(error)
})
}
}).catch((error)=>{
console.log(error)
})
promises.push(promise)
})
return Promise.all(promises).then(()=>{
console.log("All good")
}).catch((error)=>{
console.log(error)
})
}else{
console.log("Markets closed")
return
}
})

Related

Can't save Data in Json Format in Mongodb

In this application, I am saving semester_id, course_id and Subject in Mongodb. All I need is to save the Subject in Json format. I want to save semester_id , course_id and save Subject in Json(not in array) with same ids - For semeter and course. I am saving subject in array and I am new to Angular. Can anyone help me out. Thanks in advance.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectSchema = new Schema({
semesterId:{type: String,ref:'semesterNew'},
courseId :{type: String,ref:'CollegeCourse'},
subject:{
subject :{ type:String}
},
createdOn : {type:Date,default:Date.now},
updatedOn : {type:Date,default:Date.now},
});
mongoose.model('Subject',SubjectSchema);
router.post('/addSubject',function(req,res){
var subjects = JSON.stringify(req.body.subject);
var subjectData = new subjectModel({
semesterId:req.body.semesterId,
courseId: req.body.courseId,
subject: subjects,
});
subjectData.save(function (err, result) {
if (err) {
console.error(err);
return res.status(400).json({
message: 'Bad Request'
});
} else {
res.json({
status: 200,
data: result
})
console.log('Check',result);
}
});
});
addSubject(item){
return this.api.post(`${this.apiController}/addSubject`,item);
}
saveSubject() {
const config = {
position: NbGlobalPhysicalPosition.BOTTOM_RIGHT
};
const formData = new FormData();
this.subjectMasterForm.controls.semesterCtrl.markAsDirty();
this.subjectMasterForm.controls.collegeCourseCtrl.markAsDirty();
// this.subjectMasterForm.controls.image.markAsDirty();
var all_subject_array = [];
if (this.subjectMasterForm.valid && this.subjectMasterForm.value.subjects.length > 0) {
if (this.semesterSubjectId == '' || this.semesterSubjectId == null || this.semesterSubjectId == 'undefined' || this.semesterSubjectId== undefined) {
var subjects_values = this.subjectMasterForm.value.subjects
var subjects_length = this.subjectMasterForm.value.subjects.length;
subjects_values.forEach(function (element) {
all_subject_array.push(element.name);
console.log('Check2',element.name);
});
this.overview_data = {
courseId: this.courseId,
semesterId:this.semesterId,
subject: all_subject_array,
semesterSubjectId: this.semesterSubjectId,
}
this.collegeTemplateApi.addSubject(this.overview_data).subscribe(data => {
if (data['status'] == 200) {
this.toasterService.show("Subject successfully Added!!!..", `Success`, config);
} else {
this.toasterService.show("Subject Already exists in our Database!!!...", `Success`, config)
}
});
} else {
if(this.courseId!=undefined && this.semesterId!=undefined){
if (this.subjectMasterForm.value.subjects.length > 0) {
var subjects_values = this.subjectMasterForm.value.subjects
var subjects_length = this.subjectMasterForm.value.subjects.length;
subjects_values.forEach(function (element) {
all_subject_array.push(element.name);
});
this.overview_data = {
courseId: this.courseId,
semesterId:this.semesterId,
subject: all_subject_array,
semesterSubjectId: this.semesterSubjectId
}
}
this.collegeTemplateApi.updateSubject(this.overview_data).subscribe(data => {
if (data['status'] == 200) {
this.toasterService.show("Subject successfully Updated!!!..", `Success`, config);
} else {
this.toasterService.show(data['message'], `Success`, config)
}
});
}
}
} else if (this.subjectMasterForm.value.subjects.length == 0) {
this.subjecterror = true;
}
setTimeout(() => this.ngOnInit(), 3000);
}
In your first code segment, the Subject model is not assigned to a variable.
mongoose.model('Subject',SubjectSchema);
Yet later in your code you declare a new instance of subjectModel.
Try assigning the model to this name.
var subjectModel = mongoose.model('Subject', SubjectSchema);

updating and validating multiple files from different fields uploded with multer

I'm trying to update and validate a form consisting of two file inputs (one video and one image to be used as the video thumbnail) and two text inputs.
the validator and convertFiletoField were working fine when I was uploading a single file however, they have both stopped working, this is a long question but, I appreciate it, if anyone can help.
I'm using Node, epxress, mongodb and express-validator v.5.1.2
the Routes:
router.get('/mvs', mvController.index);
router.get('/mvs/create', mvController.create);
router.post('/mvs/create',
uploadVideo.fields([{
name: 'videos', maxCount: 1
}, {
name: 'images', maxCount: 1
}]),
convertFileToField.videoHandle,
mvValidator.handle(),
mvController.store
);
router.get('/mvs/:id/edit', mvController.edit);
router.put('/mvs/:id',
uploadVideo.fields([{
name: 'videos', maxCount: 1
}, {
name: 'images', maxCount: 1
}]),
convertFileToField.videoHandle,
mvValidator.handle(),
mvController.update
);
router.delete('/mvs/:id', mvController.destroy);
the Controller:
const fs = require('fs');
const path = require('path');
const controller = require('app/http/controllers/controller');
const Artist = require('app/models/artist');
const MV = require('app/models/mv');
class mvController extends controller {
async index(req , res) {
try {
let page = req.query.page || 1;
let mvs = await MV.paginate({} , { page , sort : { createdAt : 1 } , limit : 5 });
res.render('admin/mvs/index', { title : 'videos' , mvs });
} catch (err) {
next(err);
}
}
async create(req , res) {
let artists = await Artist.find({});
res.render('admin/mvs/create' , { artists });
}
async store(req , res , next) {
try {
let status = await this.validationData(req);
if(! status) {
if(req.file)
fs.unlinkSync(req.file.path);
return this.back(req,res);
}
// Create music video
let videos = this.videoPath(req.files['videos'][0]);
let images = this.videoPath(req.files['images'][0]);
let { title, artist} = req.body;
let newMV = new MV({
title,
slug : this.slug(title),
artist,
videos,
images
});
await newMV.save();
// update artist Times
this.updateArtistTime(req.body.artist);
return res.redirect('/admin/mvs');
} catch(err) {
next(err);
}
}
async edit(req, res ,next) {
try {
this.isMongoId(req.params.id);
let mv = await MV.findById(req.params.id);
let artists = await Artist.find({});
if( ! mv ) this.error('video does not exist' , 404);
return res.render('admin/mvs/edit' , { mv , artists });
} catch (err) {
next(err);
}
}
async update(req, res , next) {
try {
let status = await this.validationData(req);
if(! status) {
if(req.files)
fs.unlinkSync(req.files.path);
return this.back(req,res);
}
let objForUpdate = {};
// check video
if(req.files) {
objForUpdate.videos = this.videoPath(req.files['videos'][0]);
objForUpdate.images = this.videoPath(req.files['images'][0]);
}
delete req.body.videos;
delete req.body.images;
objForUpdate.slug = this.slug(req.body.title);
let mv = await MV.findByIdAndUpdate(req.params.id , { $set : { ...req.body, ...objForUpdate }});
// prev artist time update
this.updateArtistTime(mv.artist);
// now artist time update
this.updateArtistTime(req.body.artist);
return res.redirect('/admin/mvs');
} catch(err) {
next(err);
}
}
async destroy(req , res , next) {
try {
this.isMongoId(req.params.id);
let mv = await MV.findById(req.params.id);
if( ! mv ) this.error('video does not exist' , 404);
let artistId = mv.artist;
// delete music videos
fs.unlinkSync(`./public${mv.videos}`);
fs.unlinkSync(`./public${mv.images}`)
mv.remove();
// artist time update
this.updateArtistTime(artistId);
return res.redirect('/admin/mvs');
} catch (err) {
next(err);
}
}
async updateArtistTime(artistId) {
let artist = await Artist.findById(artistId).populate('mvs').exec();
artist.set({ time : this.getTime(artist.mvs)});
await artist.save();
}
videoPath(video) {
let addressVideos = this.getUrlVideo(`${video.destination}/${video.filename}`);
return addressVideos;
}
getUrlVideo(dir) {
return dir.substring(8);
}
slug(title) {
return title.replace(/([^۰-۹آ-یa-z0-9]|-)+/g , "-")
}
}
module.exports = new mvController();
the uploadVideo helper
const multer = require('multer');
const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirVideo = () => {
let year = new Date().getFullYear();
let month = new Date().getMonth() + 1;
let day = new Date().getDay();
return `./public/uploads/mvs/${year}/${month}/${day}`;
}
const videoStorage = multer.diskStorage({
destination : (req , file , cb) => {
let dir = getDirVideo();
mkdirp(dir , (err) => cb(null , dir))
},
filename : (req , file , cb) => {
let filePath = getDirVideo() + '/' + file.originalname;
console.log(filePath);
if(!fs.existsSync(filePath))
cb(null , file.originalname);
else
cb(null , Date.now() + '-' + file.originalname);
}
})
const uploadVideo = multer({
storage : videoStorage,
limits : {
fileSize : 1024 * 1024 * 40
}
});
module.exports = uploadVideo;
converFiletoField
videoHandle(req , res , next) {
if(! req.files) {
req.body.videos = undefined;
req.body.images = undefined;
}
else {
req.body.videos = req.files.videos[0].filename;
req.body.images = req.files.images[0].filename;
}
next();
}
Validator:
const validator = require('./validator');
const { check } = require('express-validator/check');
const Artist = require('app/models/artist');
const MV = require('app/models/mv');
const path = require('path');
class mvValidator extends validator {
handle() {
return [
check('title')
.isLength({ min : 3 })
.withMessage('title can not be less than 3 characters'),
check('artist')
.not().isEmpty()
.withMessage('related artist can not remain empty'),
check('videos')
.custom(async (value , { req }) => {
if(req.query._method === 'put' && value === undefined) return;
if(! value)
throw new Error('video can not remain empty');
let fileExt = ['.webm' , '.mp4' , '.flv' , '.avi'];
if(! fileExt.includes(path.extname(value)))
throw new Error('file extention is not acceptable');
}),
check('images')
.custom(async (value , { req }) => {
if(req.query._method === 'put' && value === undefined) return;
if(! value)
throw new Error('video thumbnail can not remain empty');
let fileExt = ['.png' , '.jpg' , '.jpeg' , '.svg'];
if(! fileExt.includes(path.extname(value)))
throw new Error('file extention is not acceptable')
})
]
}
slug(title) {
return title.replace(/([^۰-۹آ-یa-z0-9]|-)+/g , "-")
}
}
module.exports = new mvValidator();
the error I'm getting when I'm trying to update/edit
TypeError: Cannot read property '0' of undefined
at convertFileToField.videoHandle (test\app\http\middleware\convertFileToField.js:22:47)
at Layer.handle [as handle_request] (test\node_modules\express\lib\router\layer.js:95:5)
at next (E:\test\node_modules\express\lib\router\route.js:137:13)
at Immediate._onImmediate (test\node_modules\multer\lib\make-middleware.js:53:37)
at processImmediate (internal/timers.js:463:21
the error I'm getting from validator when I enter title with 2 characters instead on min of 3
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
just try create a middleware like this :
videoHandle.js
module.exports = (req, res, next) => {
try {
if (!req.files) {
req.body.videos = undefined;
req.body.images = undefined;
} else {
req.body.videos = (req.files.videos) ? req.files.videos[0].filename : undefined;
req.body.images = ( req.files.images)? req.files.images[0].filename : undefined;
}
next();
} catch (err) {
console.log(err)
const error = new HttpError("uploading failed!", 403);
return next(error);
}
};
require the middleware in the router
const videoHandle = require('./videoHandle');//path of videoHandler
router.post('/mvs/create',
uploadVideo.fields([{
name: 'videos', maxCount: 1
}, {
name: 'images', maxCount: 1
}]),
videoHandle,(req,res)=>{
//do somtethings
console.log(req.body)
}
);

AWS Lambda (NodeJS) does not log to cloudwatch

I'm trying to log my lambda app after following serverless-next.js because of the issue where I can't go to the root of my file. So basically I'm deploying nextJS app in AWS through lambda#edge, s3, and cloudfront.
I'm new to AWS so I'm not really sure how to debug this thing at all. I assume traditional console.log in my lambda where every request comes in would log it in the cloudwatch. I also made sure that I deployed my lambda to my cloud front
Here's the code:
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = void 0;
const prerender_manifest_json_1 = __importDefault(require("./prerender-manifest.json"));
const manifest_json_1 = __importDefault(require("./manifest.json"));
const next_aws_cloudfront_1 = __importDefault(require("#sls-next/next-aws-cloudfront"));
const addS3HostHeader = (req, s3DomainName) => {
req.headers["host"] = [{ key: "host", value: s3DomainName }];
};
const isDataRequest = (uri) => uri.startsWith("/_next/data");
const normaliseUri = (uri) => (uri === "/" ? "/index" : uri);
const normaliseS3OriginDomain = (s3Origin) => {
if (s3Origin.region === "us-east-1") {
return s3Origin.domainName;
}
if (!s3Origin.domainName.includes(s3Origin.region)) {
const regionalEndpoint = s3Origin.domainName.replace("s3.amazonaws.com", `s3.${s3Origin.region}.amazonaws.com`);
return regionalEndpoint;
}
return s3Origin.domainName;
};
const router = (manifest) => {
const { pages: { ssr, html } } = manifest;
const allDynamicRoutes = Object.assign(Object.assign({}, ssr.dynamic), html.dynamic);
return (uri) => {
let normalisedUri = uri;
if (isDataRequest(uri)) {
normalisedUri = uri
.replace(`/_next/data/${manifest.buildId}`, "")
.replace(".json", "");
}
if (ssr.nonDynamic[normalisedUri]) {
return ssr.nonDynamic[normalisedUri];
}
console.log(uri);
for (const route in allDynamicRoutes) {
const { file, regex } = allDynamicRoutes[route];
const re = new RegExp(regex, "i");
const pathMatchesRoute = re.test(normalisedUri);
if (pathMatchesRoute) {
return file;
}
}
if (html.nonDynamic["/404"] !== undefined) {
return "pages/404.html";
}
return "pages/_error.js";
};
};
exports.handler = (event) => __awaiter(void 0, void 0, void 0, function* () {
const request = event.Records[0].cf.request;
const uri = normaliseUri(request.uri);
const manifest = manifest_json_1.default;
const prerenderManifest = prerender_manifest_json_1.default;
const { pages, publicFiles } = manifest;
const isStaticPage = pages.html.nonDynamic[uri];
const isPublicFile = publicFiles[uri];
const isPrerenderedPage = prerenderManifest.routes[request.uri];
const origin = request.origin;
const s3Origin = origin.s3;
const isHTMLPage = isStaticPage || isPrerenderedPage;
const normalisedS3DomainName = normaliseS3OriginDomain(s3Origin);
s3Origin.domainName = normalisedS3DomainName;
if (isHTMLPage || isPublicFile) {
s3Origin.path = isHTMLPage ? "/static-pages" : "/public";
addS3HostHeader(request, normalisedS3DomainName);
if (isHTMLPage) {
request.uri = `${uri}.html`;
}
return request;
}
const pagePath = router(manifest)(uri);
if (pagePath.endsWith(".html")) {
s3Origin.path = "/static-pages";
request.uri = pagePath.replace("pages", "");
addS3HostHeader(request, normalisedS3DomainName);
return request;
}
const page = require(`./${pagePath}`);
const { req, res, responsePromise } = next_aws_cloudfront_1.default(event.Records[0].cf);
if (isDataRequest(uri)) {
const { renderOpts } = yield page.renderReqToHTML(req, res, "passthrough");
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(renderOpts.pageData));
}
else {
page.render(req, res);
}
return responsePromise;
});
Permission:
Allow: logs:CreateLogGroup
Allow: logs:CreateLogStream
Allow: logs:PutLogEvents
What else should I do? Should I create a new stream or is it automatically created? I can see a log group in my cloudwatch named aws/lambda but i'm not sure how to connect them
Really appreciate any help
Cheers

Mongodb UseUnifiedTopology: True causes connection errors in my code

I have a small app written in Node.js that downloads some data from an API, and then saves it into a MongoDB. When I have useunifiedtopology: false my code runs fine, connects to the mongodb fine and updates everything fine.
When I set useunifiedtopolgy: true I get the following errors
MongoError: Cannot use a session that has ended
Here is what I am trying to accomplish...I can't for the life of me figure out where it's going wrong. If I remove the db.close() from dbupdater.js, it works, but the app just hangs.
Here is how I am going about things...
It should also be noted, that if I remove the multiple locations and extraction calls from below, then it does work fine. The errors noted above when using useunifiedtopology: false only seem to happen when I am doing multiple calls to the dbupdater module. So, to be clear, if I just hit the API once, and do one call to dbupdater, it works fine. If I call the API and the dbupdater function multiple times, it fails with the error:
MongoError: Cannot use a session that has ended.
app.js Contents:
const Downloader = require('./modules/Downloader')
const dbupdater = require('./modules/dbUpdater')
var Locations = ['Location1','Location2']
var ExtractionTypes = ['Extraction1','Extraction2','Extraction3' ]
var interval = 60000; //API Request Delay in MS
var promise = Promise.resolve();
function main() {
Locations.forEach(location => {
promise = promise.then(function(){
ExtractionTypes.forEach(extraction =>{
promise = promise.then(function(){
talonDownloader(location,extraction,function(data){
if (data == null) {
console.log(`No ${extraction} Data Recieved for period requested.`)
}
else {
dbupdater(extraction,data)
}
})
return new Promise(function (resolve) {
setTimeout(resolve, interval)
})
})
})
return new Promise(function (resolve) {
setTimeout(resolve, interval)
})
})
})
}
main();
Then here is the code for my dbupdater...
dbudater.js
module.exports = function (extraction,data) {
const MongoClient = require('mongodb').MongoClient;
const date = require('date-and-time');
const crypto = require('crypto')
const dburl = "mongodb://localhost:27017/";
const dbName = 'palDB'
//Initialize Date Information
const now = new Date()
const todayDate = date.format(now, 'DD-MMM-YYYY')
if (extraction == 'operation') {
var collectionName = 'operations'
var indexValue = 'ACTIVITY_ID'
updateDBGeneral();
}
else if (extraction == 'aircraft') {
var collectionName = 'aircraft'
var indexValue = 'AIRCRAFT_ID'
updateDBGeneral();
updateDBHistorical();
}
else if (extraction == 'cancelanalysis') {
var collectionName = 'cancelAnalysis'
var indexValue = 'SCH_ACT_ID'
updateDBGeneral();
}
else if (extraction == 'dailyflylog') {
var collectionName = 'dfl'
var indexValue = 'SCH_ACT_ID'
updateDBGeneral();
}
else if (extraction == 'instructor') {
var collectionName = 'instructor'
var indexValue = 'ETA_ID'
updateDBGeneral();
}
else if (extraction == 'resschedproductivity') {
var collectionName = 'resSchedProductivity'
var indexValue = 'opid'
updateDBGeneral();
}
else if (extraction == 'student') {
var collectionName = 'student'
var indexValue = 'ETA_ID'
updateDBGeneral();
}
else if (extraction == 'trainingrecord') {
var collectionName = 'trgrec'
var indexValue = 'STUDENT_REGISTRATION_ID'
updateDBGeneral();
}
else if (extraction == 'studentprogression') {
var collectionName = 'studentProgression'
var indexValue = 'studentProgIndex'
updateDBGeneral();
}
//Initialize DB Updater functions
function updateDBGeneral(){
MongoClient.connect(dburl,{useNewUrlParser: true, useUnifiedTopology: true})
.then((db) => {
var dbo = db.db(dbName);
console.log(`Connection Established to ${dbo.databaseName} database.`)
data.forEach(element => {
if (indexValue == 'opid') {
element[indexValue] = crypto.createHash('md5').update(element.CAL_DATE + element.RES_TYPE_ID).digest('hex'); //Add Value to filter on
var filter = {[indexValue]: element[indexValue]};
} else if (indexValue =='studentProgIndex'){
element[indexValue] = crypto.createHash('md5').update(element.PERS_REGISTER_ID + element.UNIT + element.ACT_START).digest('hex'); //Add value to filter on
var filter = {[indexValue]: element[indexValue]}
} else var filter = {[indexValue]: element[indexValue]}
dbo.collection(collectionName)
.updateOne(filter, {$set:element},{upsert:true})
.then( result => db.close())
.catch( err => console.log(err));
})
})
.catch( err => console.log(err));
}
function updateDBHistorical(){
}
}

node js post request

Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as above

Resources