push notification with angular and nodejs - node.js

I have create push notification with angular and nodejs ..when I valid article i will send push notification to user will create article ... User1 create article and when admin valid this article user1 receive notification ... this is my code in general for receive notification but where is modification in my code for receive notification only for user1 .
code service angular:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
const SERVER_URL = 'http://localhost:3000/subscription';
#Injectable()
export class PushNotificationService {
constructor(private http: HttpClient) {}
public sendSubscriptionToTheServer(subscription: PushSubscription) {
return this.http.post(SERVER_URL, subscription);
}
}
code component:
import { Component, OnInit } from '#angular/core';
import { SwPush } from '#angular/service-worker';
import { PushNotificationService } from '../../services/push-notification.service';
const VAPID_PUBLIC = "BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI";
const PRIVATE = "D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ";
#Component({
selector: 'app-test-component',
templateUrl: './test-component.component.html',
styleUrls: ['./test-component.component.scss']
})
export class TestComponentComponent implements OnInit {
constructor(public swPush: SwPush, public pushService: PushNotificationService) {
}
test(){
if (this.swPush.isEnabled) {
this.swPush
.requestSubscription({
serverPublicKey: VAPID_PUBLIC
})
.then(subscription => {
this.pushService.sendSubscriptionToTheServer(subscription).subscribe();
})
.catch(console.error);
}
}
ngOnInit() {
}
}
code nodejs:
const express = require('express');
const webpush = require('web-push');
const cors = require('cors');
const bodyParser = require('body-parser');
const PUBLIC_VAPID = 'BJPrg7jbhWkWZn5mhg0Wti8031cHjsLGyN1G4pmfeippmEsXHo53wnRiqqjApVkA1KQyIz0IYK4ln0ie7RLrsiI';
const PRIVATE_VAPID = 'D1njq6Y7ny2QexJ-JZXbUpufCkfIywLSMvO6s-iSNoQ';
const fakeDatabase = [];
const app = express();
app.use(cors());
app.use(bodyParser.json());
webpush.setVapidDetails('mailto:mailto#gmail.com', PUBLIC_VAPID, PRIVATE_VAPID);
app.post('/subscription', (req, res) => {
const subscription = req.body;
fakeDatabase.push(subscription);
const notificationPayload = {
notification: {
title: 'New Notification',
body: 'This is the body of the notification',
icon: 'assets/icons/icon-512x512.png'
}
};
const promises = [];
fakeDatabase.forEach(subscription => {
promises.push(webpush.sendNotification(subscription, JSON.stringify(notificationPayload)));
});
fakeDatabase.length =0
Promise.all(promises).then(() => res.sendStatus(200));
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
help me and thank you for advanced

Related

IONIC post method is returning undefined value

ERROR MESSAGE
I tested the node js post on postman and it worked. However, when I made use of ionic serve, it will show the error as shown in the image above. This error occurred when I call the makePayment() function in the stripe.page.ts file. The data I retrieved through this.checkout.makePayment in the makePayment() function returns undefined. I am guessing that the issue is probably my node js isn't being triggered when I use ionic serve. Is there a way to solve this?
THIS IS MY checkout.service.ts FILE
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CheckoutService {
constructor(private http: HttpClient) { }
makePayment(stripeToken: any): Observable<any>{
const url = "http://localhost:5040/checkout"
return this.http.post<any>(url,{token:stripeToken})
}
}
THIS IS MY index.js FILE
const express = require("express");
const bodyparser = require('body-parser')
const app = express();
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
const stripe = require("stripe")("###SECRETKEY###");
const cors = require('cors')
app.use(cors())
app.post('/checkout', function(req, res) {
try {
console.log(req.body);
token = req.body.token
const customer = stripe.customers
.create({
email: "cycoplayz#gmail.com",
source: token.id
})
.then((customer) => {
console.log(customer);
return stripe.charges.create({
amount: 1000,
description: "Test Purchase using express and Node",
currency: "USD",
customer: customer.id,
});
})
.then((charge) => {
console.log(charge);
res.json({
data:"success"
})
})
.catch((err) => {
res.json({
data: "failure",
});
});
return true;
} catch (error) {
return false;
}
})
app.listen(5040, () => {
console.log("App is listening on Port 5040")
})
THIS IS MY stripe.page.ts FILE
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Loan } from '../shared/loan';
import { LoanService } from '../shared/loan.service';
import { ChargeInfo } from '../shared/models/chargeinfo';
import { CheckoutService } from '../shared/services/checkout.service';
#Component({
selector: 'app-stripe',
templateUrl: './stripe.page.html',
styleUrls: ['./stripe.page.scss'],
})
export class StripePage implements OnInit {
paymentHandler: any = null;
success: boolean = false
failure:boolean = false
loan: Loan;
loanid: string;
reason: string;
amount: number;
payment: number;
charged: ChargeInfo[] = [];
constructor(private checkout: CheckoutService, private route: ActivatedRoute, private
loanService: LoanService) {
this.loanid = this.route.snapshot.params.id
this.loanService.getChargesById(this.loanid)
.then(data =>{
this.reason = data.charges[0].reason;
this.amount = data.charges[0].amount;
})
}
ngOnInit() {
this.invokeStripe();
}
makePayment(amount: number) {
const paymentstripe = (stripeToken: any) => {
try{
this.checkout.makePayment(stripeToken).subscribe((data: any) => {
console.log(data);
if (data.data === "success") {
this.success = true
}
else {
this.failure = true
}
});
}
catch(err){
console.log(err);
console.log("hi");
}
};
const paymentHandler = (<any>window).StripeCheckout.configure({
key: '###PUBLISHABLE KEY###',
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
console.log(this.checkout.makePayment);
console.log(this.checkout.omg)
paymentstripe(stripeToken);
},
});
paymentHandler.open({
name: 'CHARGES',
description: this.reason,
amount: this.amount * 100,
});
}
invokeStripe() {
if (!window.document.getElementById('stripe-script')) {
const script = window.document.createElement('script');
script.id = 'stripe-script';
script.type = 'text/javascript';
script.src = 'https://checkout.stripe.com/checkout.js';
script.onload = () => {
this.paymentHandler = (<any>window).StripeCheckout.configure({
key: '###PUBLISHABLE KEY###',
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
},
});
};
window.document.body.appendChild(script);
}
}
}

Increase body limit with nestjs & fastify

My main.ts looks like this :
import { NestFactory } from '#nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '#nestjs/platform-fastify';
import { Logger } from 'nestjs-pino';
import { processRequest } from 'graphql-upload';
import { AppModule } from './app.module';
async function bootstrap() {
const adapter = new FastifyAdapter();
const fastifyInstance = adapter.getInstance();
fastifyInstance.addContentTypeParser('multipart', (request, done) => {
request.isMultipart = true;
done();
});
fastifyInstance.addHook('preValidation', async (request: any, reply) => {
if (!request.raw.isMultipart) {
return;
}
request.body = await processRequest(request.raw, reply.raw);
});
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
adapter,
{ bufferLogs: true },
);
app.useLogger(app.get(Logger));
app.enableCors();
await app.listen(parseInt(process.env.SERVER_PORT || '3000', 10), '0.0.0.0');
}
bootstrap();
According to the fastify doc the body limit is 1MiB by default, however I want it to be larger. So I tried like this :
const adapter = new FastifyAdapter({ bodyLimit: 124857600 }); but I still get the same problem with my payload being too large.
Try to add this when you are creating the app
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ bodyLimit: 10048576 }),

Angular 7 Form in production

I am trying to put into operation a form that sends me data to the mail with nodemailer
in localhost: 3000 it works well but when loading my project on the server with the community I can not get this code to work
an application in the root of the project called nodeMensajeria / src / node modules, app.js and configMensaje.js
mira la raiz de mi proyecto
app.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const configMensaje = require('./configMensaje');
const app = express();
app.use(bodyParser.json());
app.use(cors())
app.post('/formulario', (req, res) => {
configMensaje(req.body);
res.status(200).send();
})
app.listen(3000, () => {
console.log('Servidor corriendo')
});
configMensaje.js
const nodemailer = require('nodemailer');
module.exports = (formulario) => {
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'correoorigen',
pass: 'contraseña'
}
});
const mailOptions = {
from: `"${formulario.nombre} 👻" <${formulario.email}>`,
to: 'correodestino', //
subject: formulario.asunto,
html: `
<strong>Nombre:</strong> ${formulario.nombre} <br/>
<strong>Asunto:</strong> ${formulario.asunto} <br/>
<strong>E-mail:</strong> ${formulario.email} <br/>
<strong>Número de contacto:</strong> ${formulario.contacto} <br/>
<strong>Mensaje:</strong> ${formulario.mensaje}
`
};
transporter.sendMail(mailOptions, function (err, info) {
if (err)
console.log(err)
else
console.log(info);
});
}
the service message.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http'
#Injectable({
providedIn: 'root'
})
export class MessageService {
constructor(private _http: HttpClient) { }
sendMessage(body) {
return this._http.post('http://107.180.59.131:3000/formulario', body);
}
}
I am using the ip of my domain
app.component.ts
import { Component, OnInit } from '#angular/core';
import { MessageService } from '../services/message.service';
import swal from 'sweetalert';
import { VirtualTimeScheduler } from 'rxjs';
#Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
constructor(public _MessageService: MessageService) { }
contactForm(form) {
this._MessageService.sendMessage(form).subscribe(() => {
swal("Formulario de contacto", "Mensaje enviado correctamente", 'success');
});
}
ngOnInit() {
}
}
It shows me that the app is executed
but when sending the form in production it shows me the following error
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
main.5cb5f6b8477568c35bd7.js:1 ERROR e {headers: t, status: 0, statusText: "Unknown Error", url: "http://107.180.59.131:3000/formulario", ok: false, …}
look at the error
you have to deploy the express api into your server, this link could help you https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/deployment
you are using the developement mode to work in the production server and your firewall its blocking the port 3000, when you deploy the api, you've to send the post to http://YOUR_IP/endpoint or http://api.IP/endpoint

Angular HTTP GET not hitting Express Route

My Angular HTTP GET Request indside clearNotifications() in notification.service.ts not hitting Express Route routes/notifications.js. I am calling clearNotifications() from a component called app.component.ts. I am using Angular 7+
routes/notifications.js
const router = require('express').Router();
//Additional modules
// const db = require('../config/database');
// const notificationModel = require('../models/notifications');
//Test connection
// db.authenticate().then(() => {
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//Clear all notifications
router.get('/clear', (req, res, next) => {
console.log('clear');
// notificationModel.destroy({});
});
module.exports = router;
notification.service.ts
import { Injectable } from '#angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class NotificationService {
uri = 'http://localhost:5000';
private socket = io(this.uri);
constructor(private http: HttpClient) { }
getNotification() {
let observable = new Observable<{ string: String, number: String }>(observer => {
this.socket.on('notification', (data) => {
observer.next(data);
});
// return () => { this.socket.disconnect(); }
})
return observable;
}
clearNotifications() {
return this.http.get(`${this.uri}/notifications/clear`);
}
}
app.component.ts
import { Component } from '#angular/core';
import { NotificationService } from './notification.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [NotificationService]
})
export class AppComponent {
title = 'client';
string: String;
number: String;
notificationArray: Array<{ string: String, number: String }> = [];
constructor(private notificationService: NotificationService) {
this.notificationService.getNotification().subscribe(data => {
this.notificationArray.push(data);
});
}
clearNotifications() {
this.notificationArray = [];
this.notificationService.clearNotifications();
}
}
You should be doing this: Check the basic routing on express
var express = require('express');
var app = express();
app.get('/clear', (req, res) => {
console.log('clear');
res.send(success);
// notificationModel.destroy({});
});
Also make sure to subscribe to the service method from your component. If you do not subscribe the observables won't execute.
Where are you calling clearNotifications from?
subscribe to clearNotifications in component and this will work:
this.notificationService.clearNotifications().subscribe( (data) => { ..})
As a publisher, you create an Observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published
In angular, http request returns observable, so you need to subscribe. If there aren't any subscriber to the observable, it wont be executed. Try
clearNotifications() {
return this.http.get(`${this.uri}/notifications/clear`)
.subscribe(data => //your callback function,
error => // your error handler,
complete => // any after completion task);
}

typescript express typeorm createconnection

I am creating an app with typescript express node typeorm. I am having this issue where when I make a call through a service class to the database using typeorm, I get connection default was not found. Here are my code snippets:
//dataservice class
import { Connection, getConnection, EntityManager, Repository,
getManager } from "typeorm";
export class LeaveDataService {
private _db: Repository<Leave>;
constructor() {
this._db = getManager().getRepository(Leave);
}
/**
* applyForLeave
*/
public applyForLeave(leave: Leave): void {
if(leave !== null) {
let entity: Leave = this._db.create(leave);
this._db.save(entity);
}
}
/**
* getAllLeaves
*/
public async getAllLeaves(): Promise<Array<Leave>> {
let leaves: Promise<Array<Leave>> = this._db.find({
select: ["leaveDays","casualLeaveDays","id","staff","leaveType","endorsedBy","approvedBy"],
relations: ["staff", "leaveType"],
skip: 5,
take: 15
});
return leaves;
}
this is my ormconfig.json
{
"type":"sqlite",
"entities": ["./models/*.js"],
"database": "./leaveappdb.sql"
}
and this is the "controller" that responds to requests by calling the service class which is the first snippet:
import { Request, Response } from "express";
import { LeaveDataService } from "../services/leaveDataService";
import { LeaveIndexApiModel } from '../ApiModels/leaveIndexApiModel';
const dataService: LeaveDataService = new LeaveDataService();
export let index = async (req: Request, res: Response) => {
let result = await dataService.getAllLeaves();
let viewresult = new Array<LeaveIndexApiModel>();
result.forEach(leave => {
let apmodel =
new LeaveIndexApiModel(leave.leaveType.name,
`${leave.staff.firstname} ${leave.staff.lastname}`, leave.id);
viewresult.push(apmodel);
});
return res.status(200).send(viewresult);
}
then this is where I bootstrap my app.
import express = require('express');
import bodyParser = require('body-parser');
import path = require('path');
import * as home from './controllers/home';
import { createConnection } from 'typeorm';
import * as leavectrl from "./controllers/leaveController";
//create express server
//create app db connection.
createConnection().then(async connection => {
const app = express();
console.log("DB online!");
const approot = './';
const appport = process.env.Port || 8001;
//setup express for json parsing even with urlencoding
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(approot,'dist')));
//serve and respond to routes by api
app.get('/home', home.home);
app.get('/login',home.login);
//routes for leave
app.get('/api/leaves', leavectrl.index);
//default fall through
// app.get('*', (req: Request, res: Response)=>{
// res.sendFile(approot,'dist/index.html');
// });
app.listen(appport, ()=> console.log(`api is alive on port
${appport}`));
}).catch(error => console.log("Data Access Error : ", error));
Your configuration is seems to be good but you didn't called or used your ormconfig.json file to createConnection.
for Eg:
createConnection(./ormconfig.json).then(async connection => {
}).catch(error => console.log("Data Access Error : ", error));
Try with or i will give you a way to configure with class object to establish a DB connection
In config file:
import "reflect-metadata";
import { ConnectionOptions } from "typeorm";
import { abc } from "../DatabaseEntities/abc";
import { def } from '../DatabaseEntities/def';
export let dbOptions: ConnectionOptions = {
type: "sqlite",
name: app,
database: "./leaveappdb.sqlite3",
entities: [abc, def],
synchronize: true,
}
In server.ts
import { createConnection, createConnections } from 'typeorm';
import * as appConfig from './Config/config';
createConnection(appConfig.dbOptions).then(async connection => {
console.log("Connected to DB");
}).catch(error => console.log("TypeORM connection error: ", error));
I think this may help you..
Also, i have found that for connecting sqlite DB you are trying to connect a sql file. Kindly confirm that once too.
Thank you

Resources