how do callback from internal service with filter? - feathersjs

a help, while consuming another internal service eg:
await Promise.all (messages.map (async message => {
// Also pass the original `params` to the service call
// so that it has the same information available (e.g. who is requesting it)
message.user = await app.service ('users'). get (message.userId, params);
}));
I get all the records,
email, avatar, _id.
How do I get only email back ...?
tks

Use the $select in query. feathers select

Related

Add custom key in fetched JSON

I am making simple blog website in React and when I fetch posts I am getting user id, who posted it. with this id I am making another axios where I get user with given id and then I assign author key to my fetched posts JSON like this:
export const getPosts = async () => {
try {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
for (const item of data) {
let user = await getUser(item["userId"]);
item["author"] = user.username;
}
return data;
} catch (err) {
toast.error(err.message);
}
};
export const getUser = async (id) => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users/" + id
);
return response.data;
} catch (err) {
toast.error(err.message);
}
};
This method causes 5-10 seconds delay to display posts. I am searching for faster and simpler way to display username to every post.
U also can tell me if there is better way to fetch data and display it.
Thanks!
You have done it the exact right way if there is no other endpoint available to fetch multiple post author information at a time.
Well, this is meant to be an answer, but I'd start with a question.
Do you have access to the maintainer or developer handling the Restful API endpoint you are trying to get from?
If yes?
Tell them to simply include the author information on the response for fetching the post(s)
Or simply provide you with an endpoint that allows you to get author information for many posts at a time.
If No
Go over the documentation provided (if any) and see if there is any endpoint that allows you to fetch author information for multiple posts with a single request.
If none of the above option seems to be a way, kindly remember to block the UI When fetching the resources.
You can also fetch for few authors first and display while fetching for more in the background or on request for more by user, that way you would give a better user experience.
Happy hacking and coding 😜

How do you properly call a conditional based on the intent's displayName for dialogflow?

I am trying to do webhook fulfillment for my dialogflow agent. However there are four specific intents that should all have different JSON responses based on what specific intent is called. Right now I am creating a switch case based on the called intent's displayName. However that is not working. Should I be using a different parameter to check what intent is called other than displayName?
HERE IS MY CODE THAT ONLY OUTPUTS "test"
server.post("/get-bill-details", function(req, res) {
let intentName = req.body.queryResult.intent.displayName;
let ret = "test";
if(intentName == "1 - Bill"){
ret = "your billing amount is $120.";
}
return res.json({
fulfillmentText: ret,
source: "get-bill-details"
});
});
I would suggest you use client libraries as they will ease out the process of parsing the JSON and reduce your development time. You can use NodeJS or Python clients for Dialogflow. Also, if you need Google Assistant, you can also use following NodeJS library to build webhook. They all have documentation on how to build webhooks on cloud or by using Express and other frameworks.
Instead of matching with intent name give your intent an action name( try not to give any spaces e.g input.welcome ).
Then get the action parameter using
let action = req.body.queryResult.action;
switch(action) {
your logic..
}
Also as abhinav said you can use this library to ease your development time and better readability of your code that also help cross platform response for Cards, Image and Suggestions.
const { WebhookClient } = require('dialogflow-fulfillment');
server.post('/', function (request, response, next) {
const agent = new WebhookClient({ request, response });
const welcome = () => {
agent.add('Hello Welcome To My bot');
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
agent.handleRequest(intentMap);
}

How to send dry run notifications with vapid push notifications

GCM provides a way to send dry run messages to test the request formats, as explain in reference https://developers.google.com/cloud-messaging/http-server-ref. How can the similar dry_run support be achieved with VAPID (FCM) standard?
I know this is an old post, but I'll answer. Maybe it helps someone.
You can use DryRun to test in FCM too. Look:
// Send a message in the dry run mode.
var dryRun = true;
admin.messaging().send(message, dryRun)
.then((response) => {
// Response is a message ID string.
console.log('Dry run successful:', response);
})
.catch((error) => {
console.log('Error during dry run:', error);
});
You need to pass a bool as second parameter of send() function.

Customize Loopback response after save

I have a loopback 2.x app, in which I have a model Conversation and a model Message, with a relationship "Conversation has many messages". I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'}. I tried to use remote hook for the method __create__messages, but it did not work:
Conversation.afterRemote('__create__messages', function(ctx, next) {
ctx.result.data = {
success: 'yes'
};
next();
});
This still returns the default response. How can I return a custom json for a remote method? I have seen examples only for all models, or for all methods: multiple models, multiple methods
Maybe you can try a version of following code below. Also, I think you are meaning to to manipulate data before the method finishes, not after. If you wait, the response will already be created, preventing your intended goal. Let me know if this works (replace with methods that will work for your use case).
Conversation.observe('before save', function(context, next) {
var instance = context.instance || context.data;
if (!instance) return next();
// Your code here
next();
});

Run multiple functions based on a SINGLE form submission (method="post") using Node-express

I am looking to perform multiple actions upon receiving HTML(or EJS) form content using the POST method. I am using Node express, mongoose & mongoDB. Each of the below POST responses work individually but i am unsure how to proceed in updating multiple databases based on ONE SINGLE form submission.
// insert into passport db
app.post('/signup', passport.authenticate('local-signup',
{
successRedirect : '/index', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
//insert into my database here
[the content of in the second function is unimportant as that is working fine and has been stripped down for simplification.]
app.post('/signup', function( req, res )
{
new UserDB(
{
user_id : req.body.content,
first_name : req.body.fname,
}).save( function( err, mySite, count )
{
res.redirect( '/index' );
});
});
I have tried redirecting but the form content is not accessible after the redirect so only the first function stores the data (ie. only 1 database is filled).
How would i run both functions within
app.post('/signup',.....
{
...
});
?
Thanks in advance!
You can do this by making one function the callback of the other. This is easy because each function maintains the same Connect middleware signature, function(req, res, next), where req and res are the request and response objects created and manipulated by the application, and next is the next function to call at the end of the current function's execution.
According to the official documentation, passport.authenticate() is a normal piece of middleware. All you need to do is specify the middleware you want to be called next. Express queues middleware functions in the order in which you pass them into app.post. You can do something like this:
app.post('/signup', passport.authenticate('local-signup', {
failureRedirect : '/signup',
failureFlash : true
}),
function(req, res) {
new UserDB({
user_id : req.body.content,
first_name : req.body.fname,
}).save(function(err, mySite, count) {
res.redirect('/index');
});
});
Middleware is an extremely powerful feature of the Express framework and possibly the single most important one to master. This guide would be a great next step if you want to learn more.