How to write notification using cron.schedule inside api request - node.js

I want to give write notification within an API request. I am able to write the notification, after that I am getting message saying "Notification" but, it's not showing in application
router.post('/api/v1/getAssetDetails', async(req, res)=>{ try { emitter.emit("saveNotification", "GENERAL", { "name": "Harshad", "description": "munna", "status": "Hello", "ephemeralTeamId": 1 }); let responseObject = setResponse(true, "Notification Sent Successfully", res.statusCode); res.status(200).send(responseObject); } catch (e) { console.log(e); res.status(500).send(setResponse(false, "Internal Server Error", res.statusCode)); } })
{ "status": true, "message": "Notification Sent Successfully", "code": 200, "data": null }
Getting in the local hit, but not in the application.

Related

What is the correct JSON format for googles classroom.create?

Im trying to create a classroom using googles classroom API. Whenever run the classroom.create function I always receive the same error message. I'm using the JSON format from their docs but I just can't get it to work. I think I must be missing something.
This is the function:
async function listCourses(auth) {
const classroom = google.classroom({ version: 'v1', auth });
//Read data from JSON
let data = fs.readFileSync("class.json");
let course = JSON.parse(data);
//Try and create course
try {
const res = await classroom.courses.create(course);
console.log(res.data);
}
catch (error) {
console.log(error)
}
//List all current courses
classroom.courses.list({
pageSize: 10,
}, (err, res) => {
if (err) return console.error('The API returned an error: ' + err);
const courses = res.data.courses;
if (courses && courses.length) {
console.log('Courses:');
courses.forEach((course) => {
console.log(`${course.name} (${course.id})`);
});
} else {
console.log('No courses found.');
}
});
}
This is the JSON:
{
"id": "157942918368",
"name": "English - 9Y",
"section": "Period 2",
"ownerId": "me",
"courseState": "ACTIVE"
}
This is the error message:
code: 400,
errors: [
{
message: `Invalid JSON payload received. Unknown name "name": Cannot bind query parameter. Field 'name' could not be found in request message.\n` +
`Invalid JSON payload received. Unknown name "ownerId": Cannot bind query parameter. Field 'ownerId' could not be found in request message.\n` +
`Invalid JSON payload received. Unknown name "courseState": Cannot bind query parameter. Field 'courseState' could not be found in request message.\n` +
`Invalid JSON payload received. Unknown name "id": Cannot bind query parameter. Field 'id' could not be found in request message.\n` +
`Invalid JSON payload received. Unknown name "section": Cannot bind query parameter. Field 'section' could not be found in request message.`,
reason: 'invalid'
}
]
I believe your goal as follows.
You want to create new course using googleapis for Node.js.
Modification points:
At googleapis for Node.js, please put the request body to resource and/or requestBody.
I think that the reason of your error message is due to this.
When "id": "157942918368", is used, an error of Request contains an invalid argument. occurs.
When "courseState": "ACTIVE" is used, an error of "#CourseStateDenied This user cannot create or transition courses into the requested state." occurs.
"PROVISIONED" can be used in this case.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
const res = await classroom.courses.create(course);
To:
const res = await classroom.courses.create({ requestBody: course });
or
const res = await classroom.courses.create({ resource: course });
And also, please modify your request body as follows.
From:
{
"id": "157942918368",
"name": "English - 9Y",
"section": "Period 2",
"ownerId": "me",
"courseState": "ACTIVE"
}
To:
{
"name": "English - 9Y",
"section": "Period 2",
"ownerId": "me",
}
Note:
In this modification, it supposes that your const classroom = google.classroom({ version: 'v1', auth }); can be used for using the method of courses.create in Classroom API.
References:
Method: courses.create
googleapis for Node.js

Custom response Express Validator as JSON

I'm using Express Validator for validate user req. I'm trying to create custom response like this:
{
"code": 300,
"status": false,
"message": "Your email is not valid",
"param": "email",
"value": "kevin"
}
but what I got is
[
{
"code": 300,
"status": false,
"message": "Your email is not valid",
"param": "email",
"value": "kevin"
}
]
Here is my code:
controller.js:
const errors = validationResult(req).formatWith(utils.error);
if(!errors.isEmpty()){
res.status(300).json(errors.array());
}
ResUtils.js
error({msg, param, value, nestedErrors}) {
var code = 300;
var format = {code, status:false, message:msg, param:param, value:value, nestedErrors:nestedErrors};
return format;
}
How do I can get the response as Json, without [].
Thankyou.
Well, this state is good in my opinion, there is possibility of multiple errors so you should process all messages in a frontend app (or mobile or whatever) to give user informations about all invalid fields (or options or whatever). If you really need only a object, you can pick a first error message from an array for example.
if(!errors.isEmpty()){
const errorsArray = errors.array();
res.status(300).json(errorsArray[0]);
}
But as I said it is better approach to handle all error messages.

Route to the url when user clicks on notifications in pwa, angular 6 and web-push in Node.JS

I am working on pushing the notifications in PWA using SwPush in Angular6. For this I am using #angular/service-worker. I am able to send the notifications from node server. But when I click on the received notification, it is not able to route the desired url. I am using web-push module in node.js, and this is the payload:
"payload": {
"title": "Sample Notification",
"actions": [
{
"action": "opentweet",
"url":"https://pwa-sw-push-notifications.firebaseapp.com",
"title": "Open tweet"
}
],
"body": "A sample data to check the notification availability!",
"dir": "auto",
"icon": "https://pwa-sw-push-notifications.firebaseapp.com/assets/icons/icon-72x72.png",
"badge": "https://pwa-sw-push-notifications.firebaseapp.com/assets/icons/icon-72x72.png",
"lang": "en",
"url": "https://pwa-sw-push-notifications.firebaseapp.com",
"renotify": true,
"requireInteraction": true,
"tag": 926796012340920300,
"vibrate": [
100,
50,
100
],
"data": {
"url": "https://pwa-sw-push-notifications.firebaseapp.com",
"favorite_count": 0,
"retweet_count": 0
}
}
I am using
var webPush=require('web-push');
//sub is userSubscriptionObject to send the notifications to subscribed user browser.
webPush.sendNotification(sub, JSON.stringify(payload))))
In angular,
export class IndexComponent implements OnInit {
users: any = [];
constructor(
private http: HttpClient,
private router: Router,
private swPush: SwPush) {
console.log('this is index');
}
ngOnInit() {
this.getCoins();
}
subscribeNotifications(){
this.swPush.requestSubscription({
serverPublicKey: "BMW3STH0ODuNdhFVAZIy8FUDEwt2f8LLpWBiBnz8WE0_558rZc4aLbZUD9y-HxMlfCtyE5OD0mk3xa2oFJZu5n0"
}).then(sub => {
console.log("Notification Subscription: ", sub);
this
.http
.post('https://e1a2e469.ngrok.io/sub/subscribeNotifications', sub);.subscribe(
() => {
console.log('Sent push subscription object to server.');
},
err => console.log('Could not send subscription object to server, reason: ', err)
);
})
.catch(err => console.error("Could not subscribe to notifications", err));
}
unsubscribeNotifications(){
this.swPush.subscription.pipe(take(1)).subscribe(subscriptionValue=>{
console.log('this is un subscription', subscriptionValue);
this
.http
.post('https://e1a2e469.ngrok.io/sub/unsubscribeNotifications', subscriptionValue);
.subscribe(
res => {
console.log('[App] Delete subscriber request answer', res)
// Unsubscribe current client (browser)
subscriptionValue.unsubscribe()
.then(success => {
console.log('[App] Unsubscription successful', success)
})
.catch(err => {
console.log('[App] Unsubscription failed', err)
})
},
err => {
console.log('[App] Delete subscription request failed', err)
}
);
});
}
sendNotifications(){
console.log('subscribeNotifications')
this
.http
.post('https://e1a2e469.ngrok.io/sub/sendNotifications', null).subscribe(res=>{
console.log('subscribed successfully');
});
}
}
My intention is, when user clicks on the notification it is supposed to route to
https://pwa-sw-push-notifications.firebaseapp.com.
I have tried giving this URL in different parameters in the above object like actions[0].action.url URL data.url and nothing worked. So I am confused where to give the URL to make it possible. Could anyone help me out?
Thank you.
There's nothing wrong with your payload, as far as I can see. The payload is just a data which is delivered to your browser, on your browser side you need to implement notificationClick handler in order to process the payload data i.e., navigating to the desired URL. A simple notifictionClick handler can be implemented in service worker as follow:
this.scope.addEventListener('notificationclick', (event) => {
console.log('[Service Worker] Notification click Received. event', event);
event.notification.close();
if (clients.openWindow && event.notification.data.url) {
event.waitUntil(clients.openWindow(event.notification.data.url));
}
});
For reference check out the links below:
https://github.com/angular/angular/issues/20956#issuecomment-374133852
https://medium.com/google-developer-experts/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-2-practice-3221471269a1

AWS cognito: getCredentials not working

Im in the process of learning to use AWS Cognito. I have set up a userpool and a identity pool.
Code (simplified):
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
let cognitoGetUser = userPool.getCurrentUser();
if (cognitoGetUser != null) {
cognitoGetUser.getSession((err, result) => {
if (result) {
console.log ("Authenticated to Cognito User and Identity Pools!");
let token = result.getIdToken().getJwtToken();
let cognitoParams = {
IdentityPoolId: this.identityPool,
Logins: {}
};
cognitoParams.Logins["cognito-idp.eu-west-1.amazonaws.com/"+this.poolData.UserPoolId] = token;
AWS.config.credentials = new AWS.CognitoIdentityCredentials(cognitoParams);
AWS.config.getCredentials(() => {
console.log(AWS.config.credentials.accessKeyId)
console.log(AWS.config.credentials.secretAccessKey)
console.log(AWS.config.credentials.sessionToken)
}
}
}
}
},
onFailure: function(err) {
console.log('error');
console.log(err)
}
}
}
Most of the code works as expected: The authenticateUser fires the onSuccess and I can see a jwt token ect
Problem: I cant get the AWS.config.getCredentials to work. It executed without any errors, but accessKeyId, secretAccessKey and SessionToken are all undefined.
Any suggestions to what I'm doing wrong?
I cant get the AWS.config.getCredentials to work. It executed without any errors but,
This may be a mistaken assumption. Your abbreviated code is missing a couple of closing parentheses, but ran fine for me without any meaningful adjustments.
When calling getCredentials, any errors are "silently" reported through an error object. I would think you'd see a 400 response somewhere (network tab or console or both), but getCredentials() doesn't really report errors in a visible fashion by itself.
To see what is going wrong, you should add a parameter to the callback you pass to getCredentials():
AWS.config.getCredentials((err) => {
if (err) {
console.log(err);
} else {
console.log(AWS.config.credentials.accessKeyId)
console.log(AWS.config.credentials.secretAccessKey)
console.log(AWS.config.credentials.sessionToken)
}
});
For reference, one commonly encountered error object looks like this. Note that the useful message is found in originalError.message:
{
"message": "Could not load credentials from CognitoIdentityCredentials",
"code": "CredentialsError",
"time": "2018-06-03T15:19:02.078Z",
"requestId": "71b03b4a-6741-11e8-98af-b70a114474f8",
"statusCode": 400,
"retryable": false,
"retryDelay": 94.28032122526344,
"originalError": {
"message": "Invalid login token. Issuer doesn't match providerName",
"code": "NotAuthorizedException",
"time": "2018-06-03T15:19:02.078Z",
"requestId": "71b03b4a-6741-11e8-98af-b70a114474f8",
"statusCode": 400,
"retryable": false,
"retryDelay": 94.28032122526344
}
}
The corresponding 400 in the Network tab contains this response:
{"__type":"NotAuthorizedException","message":"Invalid login token. Issuer doesn't match providerName"}

Admin Firebase updateUser() Node SDK

I am trying to update login data from a firebase user using the Node admin sdk. My code looks like this:
    
var uid = req.body.uid
var objectUpdate = { "displayName": "David Coelho"};
admin.auth().updateUser(uid, objectUpdate)
  .then (function (userRecord) {
      //var id = userRecord.uid;
      //usersRef.child(id).set(userDatabase (req, res))
      res.status(200).json({ "return": "Success update user"})
  })
  .catch(function (error) {
      res.status(500).json({ "return": error})
  });
But I can not update the user. Firebase sends me the following error message:
"Code": "auth / internal-error",
"Message": "An internal error has occurred."
Can someone help me?

Resources