Error 500 in Firebase functions during Like & Dislike feature - javascript

I am currently watching a tutorial bought from udemy, and during the implementation, I encountered a problem while implementing the Like or Dislike feature.
When I make a post request to a Firebase function I get a error 500 in the console, and in the Firebase functions logs I see this error:
Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
at Object.validateResourcePath (/srv/node_modules/#google-cloud/firestore/build/src/path.js:403:15)
at CollectionReference.doc (/srv/node_modules/#google-cloud/firestore/build/src/reference.js:1718:20)
at exports.updateLikesCount.functions.https.onRequest (/srv/lib/index.js:24:44)
at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
at /worker/worker.js:783:7
at /worker/worker.js:766:11
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)
Index.js file functions for firebase
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
export const updateLikesCount = functions.https.onRequest((request, response) => {
console.log(request.body);
const eventId = request.body.eventId;
const userId = request.body.userId;
const state = request.body.state; //like or unlike
// tslint:disable-next-line: no-floating-promises
admin.firestore().collection("events").doc(eventId).get().then((data: any) => {
let likesCount = data.data().likesCount || 0;
let likes = data.data().likes || [];
let updateData = {} as any;
if (state === "like") {
updateData["likesCount"] = ++likesCount;
updateData[`likes.${userId}`] = true;
}
else {
updateData["likesCount"] = --likesCount;
updateData[`likes.${userId}`] = false;
}
admin.firestore().collection("events").doc(eventId).update(updateData).then(() => {
response.status(200).send("Done");
}).catch((err) => {
response.status(err.code).send(err.message);
})
}).catch((err) => {
response.status(err.code).send(err.message);
})
})
Feed.html
<div class = "content" *ngFor="let event of events">
<ion-button (click)="like(event)">Like</ion-button>
...
Feed.page.ts
like(event) {
let body = {
eventId: event.id,
userId: firebase.auth().currentUser.uid,
state: event.data().likes && event.data().likes[firebase.auth().currentUser.uid] == true ? "unlike" : "like",
}
// tslint:disable-next-line: max-line-length
this.http.post("https://us-central1-cp-eventoo.cloudfunctions.net/updateLikesCount", JSON.stringify(body), { responseType: "text" }).subscribe((data) => { //third parameter represents the response(200) in functions
console.log(data)
}, (error) => {
console.error(error.status);
})
}
When i click like button i get Error 500, when i test with postman i get this error:
Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
at Object.validateResourcePath (/srv/node_modules/#google-cloud/firestore/build/src/path.js:403:15)
at CollectionReference.doc (/srv/node_modules/#google-cloud/firestore/build/src/reference.js:1718:20)
at exports.updateLikesCount.functions.https.onRequest (/srv/lib/index.js:24:44)
at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
at /worker/worker.js:783:7
at /worker/worker.js:766:11
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)

if (typeof (request.body) === 'string') {
body = JSON.parse(request.body);
} else {
body = request.body;
}
By adding these lines of code the problem is gone.Thanks!

if (!is.string(resourcePath) || resourcePath === '') {
throw new Error(`Path must be a non-empty string.`);
}
This is the line that is failing for you, your postman raw data needs to be in JSON format. By default is set to text, it must be changed to JSON(application/json)
Also, make sure your function returns a promise
export const updateLikesCount = functions.https.onRequest((request, response) => {
console.log(request.body);
const eventId = request.body.eventId;
const userId = request.body.userId;
const state = request.body.state; //like or unlike
return admin.firestore().collection("events").doc(eventId).get().then((data: any) => {
let likesCount = data.data().likesCount || 0;
let likes = data.data().likes || [];
let updateData = {} as any;
if (state === "like") {
updateData["likesCount"] = ++likesCount;
updateData[`likes.${userId}`] = true;
}
else {
updateData["likesCount"] = --likesCount;
updateData[`likes.${userId}`] = false;
}
return admin.firestore().collection("events").doc(`${eventId}`).update(updateData).then(() => {
response.status(200).send("Done");
}).catch((err) => {
response.status(err.code).send(err.message);
})
}).catch((err) => {
response.status(err.code).send(err.message);
})
})
I added a couple of return statements for your functions knows when to be finished, also ensure the doc is using the eventId as a string.
Lastly, I dont need to JSON.stringify(body) your payload, sending the object as it is it;s perfectly fine.

Related

Mock server error - The script has an unsupported MIME type ('text/html')

When i running my app i get this error :
I'm using msw versin: 0.39.2
My msw file in the public folder :
and this is my msw file :
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker (0.39.2).
* #see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/
const INTEGRITY_CHECKSUM = '*****'
const bypassHeaderName = '*****'
const activeClientIds = new Set()
self.addEventListener('install', function () {
return self.skipWaiting()
})
self.addEventListener('activate', async function (event) {
return self.clients.claim()
})
self.addEventListener('message', async function (event) {
const clientId = event.source.id
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll()
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: INTEGRITY_CHECKSUM,
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: true,
})
break
}
case 'MOCK_DEACTIVATE': {
activeClientIds.delete(clientId)
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
// Resolve the "main" client for the given event.
// Client that issues a request doesn't necessarily equal the client
// that registered the worker. It's with the latter the worker should
// communicate with during the response resolving phase.
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (client.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll()
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
async function handleRequest(event, requestId) {
const client = await resolveMainClient(event)
const response = await getResponse(event, client, requestId)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const clonedResponse = response.clone()
sendToClient(client, {
type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
ok: clonedResponse.ok,
status: clonedResponse.status,
statusText: clonedResponse.statusText,
body:
clonedResponse.body === null ? null : await clonedResponse.text(),
headers: serializeHeaders(clonedResponse.headers),
redirected: clonedResponse.redirected,
},
})
})()
}
return response
}
async function getResponse(event, client, requestId) {
const { request } = event
const requestClone = request.clone()
const getOriginalResponse = () => fetch(requestClone)
// Bypass mocking when the request client is not active.
if (!client) {
return getOriginalResponse()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return await getOriginalResponse()
}
// Bypass requests with the explicit bypass header
if (requestClone.headers.get(bypassHeaderName) === 'true') {
const cleanRequestHeaders = serializeHeaders(requestClone.headers)
// Remove the bypass header to comply with the CORS preflight check.
delete cleanRequestHeaders[bypassHeaderName]
const originalRequest = new Request(requestClone, {
headers: new Headers(cleanRequestHeaders),
})
return fetch(originalRequest)
}
// Send the request to the client-side MSW.
const reqHeaders = serializeHeaders(request.headers)
const body = await request.text()
const clientMessage = await sendToClient(client, {
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
method: request.method,
headers: reqHeaders,
cache: request.cache,
mode: request.mode,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body,
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
},
})
switch (clientMessage.type) {
case 'MOCK_SUCCESS': {
return delayPromise(
() => respondWithMock(clientMessage),
clientMessage.payload.delay,
)
}
case 'MOCK_NOT_FOUND': {
return getOriginalResponse()
}
case 'NETWORK_ERROR': {
const { name, message } = clientMessage.payload
const networkError = new Error(message)
networkError.name = name
// Rejecting a request Promise emulates a network error.
throw networkError
}
case 'INTERNAL_ERROR': {
const parsedBody = JSON.parse(clientMessage.payload.body)
console.error(
`\
[MSW] Uncaught exception in the request handler for "%s %s":
${parsedBody.location}
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
`,
request.method,
request.url,
)
return respondWithMock(clientMessage)
}
}
return getOriginalResponse()
}
self.addEventListener('fetch', function (event) {
const { request } = event
const accept = request.headers.get('accept') || ''
// Bypass server-sent events.
if (accept.includes('text/event-stream')) {
return
}
// Bypass navigation requests.
if (request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been deleted (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
const requestId = uuidv4()
return event.respondWith(
handleRequest(event, requestId).catch((error) => {
if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
request.url,
)
return
}
// At this point, any exception indicates an issue with the original request/response.
console.error(
`\
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
`${error.name}: ${error.message}`,
)
}),
)
})
function serializeHeaders(headers) {
const reqHeaders = {}
headers.forEach((value, name) => {
reqHeaders[name] = reqHeaders[name]
? [].concat(reqHeaders[name]).concat(value)
: value
})
return reqHeaders
}
function sendToClient(client, message) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(JSON.stringify(message), [channel.port2])
})
}
function delayPromise(cb, duration) {
return new Promise((resolve) => {
setTimeout(() => resolve(cb()), duration)
})
}
function respondWithMock(clientMessage) {
return new Response(clientMessage.payload.body, {
...clientMessage.payload,
headers: clientMessage.payload.headers,
})
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0
const v = c == 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
Any help?
The problem was in my package.json
When you add homepage to the package.json, the msw don't know the url.
I removed the homepage and restart my app.
The issue is your web-server: it’s returning a Content-type of 'text-html'. I bet you have misspelled the name of the script and it’s sending an HTML 404 page.

TypeError: [] is not a function [duplicate]

This question already has answers here:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Closed last year.
I am making a Discord bot command handler, and I keep getting this error:
(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
^
TypeError: [] is not a function
Here is my code:
const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js')
const { promisify } = require("util")
const { glob } = require('glob');
const PG = promisify(glob)
const Ascii = require('ascii-table')
/**
* #param {Client} client
*/
module.exports = async (client) => {
const Table = new Ascii('Command Loaded')
CommandsArray = []
(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {
const command = require(file);
if (!command.name)
return Table.addRow(file.split("/")[7], 'FAILED', 'Missing a name.')
if (!command.description)
return Table.addRow(command.name, 'FAILED', 'Missing the description.')
if (command.permission) {
if (Perms.includes(command.permission))
command.defaultPermission = false;
else
return Table.addRow(command.name,'FAILED','Permission is invalid')
}
client.commands.set(command.name, command);
CommandsArray.push(command);
await Table.addRow(command.name, 'SUCCESSFUL');
})
console.log(Table.toString())
// Permissions check //
client.on('ready', async() => {
const MainGuild = await client.guilds.cache.get('940180806696058910');
MainGuild.commands.set(CommandsArray).then(async (command) => {
const Roles = (commandName) => {
const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission
if (!cmdPerms) return null;
return MainGuild.roles.cache.filter((r) => r.permissions.has(cmdPerms))
}
const fullPermissions = command.reduce((accumulator, r) => {
const roles = Roles(r.name);
if (!roles) return accumulator;
const permissions = roles.reduce((a, r) => {
return [...a,{id: r.id, type: 'ROLE', permission: true}]
}, [])
return [...accumulator, {id: r.id, permissions}]
}, [])
await MainGuild.commands.permissions.set({ fullPermissions });
})
})
}
I've done some googling, but I was unable to find anything related to just [], type error usually appears when there is a spelling mistake in your code. I have gone through my code numerous times and have been completely unable to find any mistakes, I just cannot figure this out.
I would really appreciate some help, thank you!
Please use semi-colons!
Add ; onto the line above the PG where you define an empty array, JS sees the array and also brackets right after and this thinks you are executing a function because JS when compiled does not look at lines or spacing.
CommandsArray = [];
(await PG(`${process.cwd()}/Commands/*/*js`)).map(async (file) => {

Unexpected token " in JSON error when scheduling a Cloud function with Google Cloud Tasks

Here is my first function which listens for a firestore document to be created and then creates a new Google Cloud Task with the appropriate data.
exports.onCreatePost = functions.firestore.document('/posts/{documentId}').onCreate(async (snapshot) => {
const data = snapshot.data()
console.log('data:', data)
const expiresIn = data.expiresIn
console.log('expiresIn:', expiresIn)
//const expiresAt = data.expiresAt
let expirationAtSeconds
if (expiresIn && expiresIn > 0) {
expirationAtSeconds = Date.now() / 1000 + expiresIn
console.log('expirationAtSeconds:', expirationAtSeconds)
}
/*else if (expiresAt) {
expirationAtSeconds = expiresAt.seconds
}*/
if (!expirationAtSeconds) {
// No expiration set on this document
return
}
// Get the project ID from the FIREBASE_CONFIG env var
const project = 'project-name'
const location = 'us-central1'
const queue = 'firestore-ttl'
const tasksClient = new CloudTasksClient()
const queuePath = tasksClient.queuePath(project, location, queue)
const url = `https://${location}-${project}.cloudfunctions.net/firestoreTtlCallback`
const docPath = snapshot.ref.path
const payload = docPath
const body = Buffer.from(JSON.stringify(payload)).toString('base64')
console.log('payload:', payload)
console.log('payload:', body)
const task = {
httpRequest: {
httpMethod: 'POST',
url: url,
body: body,
headers: {
'Content-Type': 'application/json',
}
},
scheduleTime: {
seconds: expirationAtSeconds
}
}
console.log('task:', task)
const [response] = await tasksClient.createTask({ parent: queuePath, task: task})
console.log('task created:', response)
})
Here is the second function which is supposed to delete the document after a certain time. (Time received from the Google Cloud Tasks)
exports.firestoreTtlCallback = functions.https.onRequest(async (req, res) => {
console.log('Delete callback called')
const payload = req.body
console.log('payload', payload)
try {
await admin.firestore().doc(payload.docPath).delete()
res.send(200)
}
catch (error) {
console.error(error)
res.status(500).send(error)
}
})
This is the error I see in the Google Cloud Console after the task calls firestoreTtlCallback
SyntaxError: Unexpected token " in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/layers/google.nodejs.functions-framework/functions-framework/node_modules/body-parser/lib/types/json.js:158)
at parse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/body-parser/lib/types/json.js:83)
I am following this example How to schedule a Cloud Function to run in the future with Cloud Tasks
I can't figure out what could be wrong with the JSON. I assume it is something to do with what is inside the http request but I don't seem to see anything wrong. Any help or assistance would be greatly appreciated.

Node.js TypeError: Cannot read property 'author' of undefined

(UPDATED)
Problem:
I can't return all my testing data (as the picture shows)
No data show up
What I expected should be ->
{"data":[{"id": 1,"title": "title A","content": "content A","createTime": 1612708329045,"author": "Alisa"}, {"id": 2,"title": "title B","content": "content B","createTime": 1612708333855,"author": "Alisa"}],"errno":0}
Error message from terminal:
PS C:\Users\jiann\Desktop\JS\Nodejs> node www.js
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'C:\Users\jiann\Desktop\JS\Nodejs\www.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
I don't know where went wrong :(.
Please let me know if more details are needed, appreciate your help!
My code is below:
Code Block 1 Description:
If getting data and message successfully, show "errno":0, if not then show "errno":-1
class BaseModel {
constructor(data, message) {
if (typeof data === 'string') {
this.message = data
data = null
message = null
}
if (data) {
this.data = message
}
if (message) {
this.message = message
}
}
}
class SuccessModel extends BaseModel {
constructor(data, message) {
super(data, message)
this.errno = 0
}
}
class ErrorModel extends BaseModel {
constructor(data, message) {
super(data, message)
this.errno = -1
}
}
module.exports = {
SuccessModel,
ErrorModel
}
Code Block 2 Description:
set router for my blog and user. This code block will set data format in JSON, set URL path, parse query, and return 404 if no router is found.
const querystring = require('querystring')
const handleBlogRouter = require('./blog-1/src/router/blog')
const handleUserRouter = require('./blog-1/src/router/user')
const serverHandle = (req, res) => {
// set JSON
res.setHeader('Content-type', 'application/json')
//get path
const url = req.url
req.path = url.split('?')[0]
//parse query
req.query = querystring.parse(url.split('?')[0])
//set blog router
const blogData = handleBlogRouter(req, res)
if (blogData) {
res.end(
JSON.stringify(blogData)
)
return
}
//set user router
const userData = handleUserRouter(req, res)
if (userData) {
res.end(
JSON.stringify(userData)
)
return
}
//no router
res.writeHead(404, {"Content-type": "text/plain"})
res.write("404 Not Found\n")
res.end()
}
module.exports = serverHandle
Code Block 3 Description:
Use GET and POST to require data from path ->
'/api/blog/list'
'/api/blog/detail'
'/api/blog/new'
'/api/blog/update'
'/api/blog/del'
const { getList, getDetail } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const handleBlogRouter = (req, res) => {
const method = req.method // GET POST
if (method === 'GET' && req.path === '/api/blog/list') {
const author = req.query.author || ''
const keyword = req.query.keyword || ''
const listData = getList(author, keyword)
return new SuccessModel(listData)
}
if (method === 'GET' && req.path === '/api/blog/detail') {
const id = req.query.id
const data = getDetail(id)
return new SuccessModel(data)
}
if (method === 'POST' && req.path === '/api/blog/new') {
return {
msg: 'dummy'
}
}
if (method === 'POST' && req.path === '/api/blog/update') {
return {
msg: 'dummy'
}
}
if (method === 'POST' && req.path === '/api/blog/del') {
return {
msg: 'dummy'
}
}
}
module.exports = handleBlogRouter)
Code Block 4 Description:
These are my two testing data.
const getList = (author, keyword) => {
//fake data
return [
{
id: 1,
title: 'title A',
content: 'content A',
createTime: 1612708329045,
author: 'Alisa'
},
{
id: 2,
title: 'title B',
content: 'content B',
createTime: 1612708333855,
author: 'Amanda'
}
]
}
module.exports = {
getList
})
This error means you are accessing <?>.author, but <?> is undefined.
For example, if your error is here:
if (method === 'GET' && req.path === '/api/blog/list') {
const author = req.query.author || ''
// ^^^ TypeError: Cannot read property 'author' of undefined
const keyword = req.query.keyword || ''
This means req.query is undefined. You can use optional chaining if there is a chance something will be present:
let foo = undefined;
foo.bar; // TypeError: Cannot read property 'bar' of undefined
foo?.bar; // => undefined
foo?.bar.baz; // TypeError: Cannot read property 'baz' of undefined
foo?.bar?.baz; // => undefined
the error is because your server hasn't started properly so all those values you are expecting will be not a available. what command did you use to start the server?

Javascript TypeError: var is not a function

Working with Vanilla NodeJS. (i.e. no framework)
Have a function in index.js called toData() that I want to use inside an event handler.
the toData() function is exported as the default export in index.js.
The relevant portions of index.js looks like this:
function pushToData(input, title) {
data[title] = input;
console.log(data);
if (isDataFull()) {
mainEvents.emit("format-export");
}
}
module.exports = pushToData;
The file where I'm importing and attempting to use it looks like this:
const mssql = require("mssql");
const events = new require("events");
const tagList = require("./tag");
const toData = require("./index");
const tagEvents = new events.EventEmitter();
const sqlAuth = {
/*....SQL Auth Details....*/
};
tagEvents.on("b2bloaded", function(data) {
data = tagList(data, "ESB", "CustomerID");
toData(data, "B2B");
});
/*....Additional event handlers omitted due to similarity...*/
function generateSqlData(item) {
const pool = new mssql.ConnectionPool(sqlAuth, err => {
switch (item) {
case "B2B":
pool
.request()
.query(
`select top (100) * from [AspDotNetStoreFrontB2B].[dbo].[Customer]`
)
.then(res => {
tagEvents.emit("b2bLoaded", res.recordset);
})
.catch(err => console.error(err));
break;
/*....Other Cases Omitted as they operate similar....*/
default:
break;
}
});
}
module.exports = {
generateSqlData
};
The big issue is that I get a:
null: TypeError: toData is not a function message: "toData is not a function" stack: "TypeError: toData is not a function
at EventEmitter.<anonymous> (c:\Users\rutherfordc\Documents\GitHub\Migratron\sql-actions.js:36:3)
at EventEmitter.emit (events.js:160:13)
at pool.request.query.then.res (c:\Users\rutherfordc\Documents\GitHub\Migratron\sql-actions.js:87:23)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)"
proto: Error {constructor: , name: "TypeError", message: "", …}
I'm not sure why it's not running as expected. Why is the function not defined properly, or not running when called?
I suggest to export your fonction like this :
export.pushToData(input, title) {
data[title] = input;
console.log(data);
if (isDataFull()) {
mainEvents.emit("format-export");
}
}
and use it this way :
const mssql = require("mssql");
const events = new require("events");
const tagList = require("./tag");
const toData = require("./index");
const tagEvents = new events.EventEmitter();
const sqlAuth = {
/*....SQL Auth Details....*/
};
tagEvents.on("b2bloaded", function(data) {
data = tagList(data, "ESB", "CustomerID");
toData.pushToData(data, "B2B");
});

Categories

Resources