How can I change response body in nodejs? - node.js

This is the scenario where I am storing several attributes into the database. Now, while I fetch the response I don't want the exact attribute name what's already stored in Db. For eg, below is my code. Here, I have stored fields as 'ca_xyz'.Now while fetching the response I want only only 'xyz' as fieldname. Can anyone help me?
// --------adding customer group--------
const addCustomerGroup = async(req,res,next) => {
try{
console.log(req.body)
let data = await Group.create({
cg_name:req.body.name,
cg_description:req.body.description,
cg_is_active: req.body.is_ctive,
cg_created_by: req.body.created_by,
cg_modified_by: req.body.modified_by
})
var newData = {};
for (const [key, value] of Object.entries(data)) {
newData[key.substr("cg_".length)] = value;
}
console.log(newData)
res.send({
status:"success",
message:"Added customer group"
})
}
catch(error){
console.log(error)
res.send({
status:"failed",
message:"An error occurred"
})
}
}

Related

Change placeholder text after table has loaded. Hence, two values for placeholder text

How can I change placeholder text after table has loaded? No jQuery.
Ideal steps:
Table loads. No data. Placeholder says: "Fetching data"
JSONdata is fetched using:
// Script
const getJSON = async url => {
try {
const response = await fetch(url);
if(!response.ok)
throw new Error(response.statusText);
const data = await response.json();
return data;
} catch(error) {
return error;
}
};
// HTML
var table = new Tabulator("#example", {
ajaxLoader: false,
data:JSONdata,
...
...
}
getJSON('https://...').then(JSONdata => {
table.replaceData(JSONdata);
}).catch(error => {
console.error(error);
});
Placeholder text changes to: "No results found."
P.S. This feature is important when JSON fails or no search results are found. I have added a search function that only shows matched rows.
table.options.placeholder.firstElementChild.textContent = 'No results found.';
Probably should be in a getJSON.then() block.

Request Body Read Multiple Value on Node Js

i am new in NodeJs development,
i want to ask, surely this is kinda basic, but i dont know how to do it.
i have a task to read request one field that can filled with multiple values,
on json array like this :
{
"email" : "first#mail.com" , "second#mail.com", "third#mail.com"
}
how to get each value from that "email" field and processing it to some function ?
i have a query select to get username from one table
select username from [dbo].[users] where email=#email (first, second, and third)
this is my code for now only that read one value, not multiple :
async getValueFunction(req, res) {
res.setHeader('Content-Type', 'application/json');
try {
if (req.body.email != "") {
const pool = await poolPromise
const result = await pool.request()
.input('email', sql.VarChar, req.body.email)
.query(queries.getUserScoreByEmail)
var showUserScore = result.recordset;
res.json(showUserScore);
} else if (req.body.email == "") {
const pool = await poolPromise
const result = await pool.request()
.query(queries.getUserScore)
var showAllUserScore = result.recordset;
res.json(showAllUserScore);
}
} catch (error) {
res.status(500)
res.send(error.message)
}
}
how to do the loop (iteration) and collect the result/recordset before send as one response (json) ??
You should update your structure because it is not an key value pair.
What you can do is storing the E-Mail Adresses in an Array like this
const data ={
"email" : ["first#mail.com" , "second#mail.com", "third#mail.com" ]
}
And then you access it with data.email

Cannot Put error in postman..May I know what's the error..I have no problem in post and get request

/This is code that used to put request and change the team name
I don't know what is the question and I try many times and it keeps coming out cannot put error.../
obj.put('api/team/:number', (req,res)=>{
const tim = teams.find(t => t.number === parseInt(req.params.number))
if (!tim)
res.status(404).send("The team with the given number is not exist!");
const { error, value } = validationdata(req.body);
if (error){
res.send(error + "\nPlease try again!");
return;
}
tim.Team= req.body.Team;
res.send(tim);
});
function validationdata(nama){
const schema = Joi.object({
"Team" : Joi.string().min(5).max(20).required()
});
//const results = schema.validate(req.body);
return schema.validate(req.body);
};

How to push notifications in firebase node.js cloud functions?

I want to create a function with node.js but I've got stuck at a point.
Explanation of what I want to do:
First, the function will trigger when a new document added to the path profile/{profileID}/posts/{newDocument}
the function will send a notification to all the following users. the problem comes here.
I've another collection in the profile collection which is followers and contains documents of the field followerID.
I want to take this followerID and use it as a document id to access the tokenID field with I've added to the profile document.
like this:
..(profile/followerID).get(); and then access the field value of tokenID field.
My current Code:- Index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.fcmTester = functions.firestore.document('profile/{profileID}/posts/{postID}').onCreate((snapshot, context) => {
const notificationMessageData = snapshot.data();
var x = firestore.doc('profile/{profileID}/followers/');
var follower;
x.get().then(snapshot => {
follower = snapshot.followerID;
});
return admin.firestore().collection('profile').get()
.then(snapshot => {
var tokens = [];
if (snapshot.empty) {
console.log('No Devices');
throw new Error('No Devices');
} else {
for (var token of snapshot.docs) {
tokens.push(token.data().tokenID);
}
var payload = {
"notification": {
"title": notificationMessageData.title,
"body": notificationMessageData.title,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.title,
"message": notificationMessageData.title
}
}
return admin.messaging().sendToDevice(tokens, payload)
}
})
.catch((err) => {
console.log(err);
return null;
})
});
my firestore database explanation.
profile | profileDocuments | posts & followers | followers collection documents & posts collection documents
I have a parent collection called profile and it contains documents as any collection these documents contain a field called tokenID and that I want to access, but I will not do this for all users only for followers (the users who follwed that profile) so I've created a new collection called followers and it contains all the followers IDs, I want to take every followerID and for each id push tokenID to tokens list.
If I understand correctly your question, you should do as follows. See the explanations below.
exports.fcmTester = functions.firestore.document('profile/{profileID}/posts/{postID}').onCreate((snapshot, context) => {
const notificationMessageData = snapshot.data();
const profileID = context.params.profileID;
// var x = firestore.doc('profile/{profileID}/followers/'); //This does not point to a document since your path is composed of 3 elements
var followersCollecRef = admin.firestore().collection('profile/' + profileID + '/followers/');
//You could also use Template literals `profile/${profileID}/followers/`
return followersCollecRef.get()
.then(querySnapshot => {
var tokens = [];
querySnapshot.forEach(doc => {
// doc.data() is never undefined for query doc snapshots
tokens.push(doc.data().tokenID);
});
var payload = {
"notification": {
"title": notificationMessageData.title,
"body": notificationMessageData.title,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.title,
"message": notificationMessageData.title
}
}
return admin.messaging().sendToDevice(tokens, payload)
});
First by doing var x = firestore.doc('profile/{profileID}/followers/'); you don't declare a DocumentReference because your path is composed of 3 elements (i.e. Collection/Doc/Collection). Note also that,in a Cloud Function, you need to use the Admin SDK in order to read other Firestore documents/collections: So you need to do admin.firestore() (var x = firestore.doc(...) will not work).
Secondly, you cannot get the value of profileID just by doing {profileID}: you need to use the context object, as follows const profileID = context.params.profileID;.
So, applying the above, we declare a CollectionReference followersCollecRef and we call the get() method. Then we loop over all the docs of this Collection with querySnapshot.forEach() to populate the tokens array.
The remaining part is easy and in line with your code.
Finally, note that since v1.0 you should initialize your Cloud Functions simple with admin.initializeApp();, see https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin
Update following your comments
The following Cloud Function code will lookup the Profile document of each follower and use the value of the tokenID field from this document.
(Note that you could also store the tokenID directly in the Follower document. You would duplicate data but this is quite common in the NoSQL world.)
exports.fcmTester = functions.firestore.document('profile/{profileID}/posts/{postID}').onCreate((snapshot, context) => {
const notificationMessageData = snapshot.data();
const profileID = context.params.profileID;
// var x = firestore.doc('profile/{profileID}/followers/'); //This does not point to a document but to a collectrion since your path is composed of 3 elements
const followersCollecRef = admin.firestore().collection('profile/' + profileID + '/followers/');
//You could also use Template literals `profile/${profileID}/followers/`
return followersCollecRef.get()
.then(querySnapshot => {
//For each Follower document we need to query it's corresponding Profile document. We will use Promise.all()
const promises = [];
querySnapshot.forEach(doc => {
const followerDocID = doc.id;
promises.push(admin.firestore().doc(`profile/${followerDocID}`).get()); //We use the id property of the DocumentSnapshot to build a DocumentReference and we call get() on it.
});
return Promise.all(promises);
})
.then(results => {
//results is an array of DocumentSnapshots
//We will iterate over this array to get the values of tokenID
const tokens = [];
results.forEach(doc => {
if (doc.exists) {
tokens.push(doc.data().tokenID);
} else {
//It's up to you to decide what you want to to do in case a Follower doc doesn't have a corresponding Profile doc
//Ignore it or throw an error
}
});
const payload = {
"notification": {
"title": notificationMessageData.title,
"body": notificationMessageData.title,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.title,
"message": notificationMessageData.title
}
}
return admin.messaging().sendToDevice(tokens, payload)
})
.catch((err) => {
console.log(err);
return null;
});
});

Add parent child whenever onchild created cloud function real time database

Here I have code that trigger ref /tugas_course/{course_id}/{tugas_id} whenever child added will send notification to the android device. It already doing really well. But I want to add one more function inside it, I want to add child outside this ref called flag_tugas and will be populate with flag_tugas-course_id-tugas_id-user.uid: "o". I dont know how to add it, because the return value already take it all and how to get users id in cloud function.
export const onNotifTugas = functions.database.ref('/tugas_course/{course_id}/{tugas_id}')
.onCreate((snapshot, context) =>{
const course_id = context.params.course_id;
const tugas_id = context.params.tugas_id;
console.log(`New Message ${course_id} in ${tugas_id}`);
return admin.database().ref('/tugas/' + tugas_id +'/').once('value').then(snap => {
const tugasData = snap.val();
const notifDataSend = { // buat structure data json dgn nama const notifDataSend untul cloud messaging
data: {
data_type: "tugas",
title: "Anda mendapatkan notifikasi baru..", // data bebas (key, value)
body: `Tugas ${tugasData.nama_tugas} baru`, // chatId = const chatId
sound: "default"
}
};
console.log(`data yang dikirim `);
return admin.messaging().sendToTopic(course_id, notifDataSend)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
}).catch(error => {
console.log(error);
})
});
}
Actually adding the new child under eclassapp
Really thanks for your time and answer..
I am not sure to fully understand where you want to add the timestamp in your node tree (under /tugas_course/{course_id}/{tugas_id}/new_child or under /tugas_course/{course_id}/{tugas_id}) but the following code will work for adding a timestamp value right under /tugas_course/{course_id}/{tugas_id}. If you need you can change the value of ref to write the timestamp where you want.
exports.onNotifTugas = functions.database
.ref('/tugas_course/{course_id}/{tugas_id}')
.onCreate((snapshot, context) => {
const ref = snapshot.ref;
const ts = admin.database.ServerValue.TIMESTAMP;
return ref.update({
date_time: ts
});
});
Note however that you don't need a Cloud Function to add a timestamp from the server, see https://firebase.google.com/docs/reference/js/firebase.database.ServerValue
So in your case you would do something like:
var tugaRef = firebase.database().ref("/tugas_course/course_id/tugas_id");
tugaRef.push({
foo: bar, //Other data of your 'tugas' object
createdAt: firebase.database.ServerValue.TIMESTAMP
})

Resources