Stop node mailer scheduler after 3 days of subscribing to newsletter - node.js

I have a node.js application and I am using node mailer. When user subscribes to newsletter I send him newsletter every day at specific hour. How can I achieve that it will stop sending to that specific user after 3 days.
Code in MailServiceCron.ts:
export const CRON = () => {
scheduleJob("0 5 * * *", async () => {
try {
let UserList = await User.getUsersByDate();
UserList.forEach(async (user: IUserGet) => {
var content = fs.readFileSync("src/data/email.html");
var htmlbody = content.toString();
await fetch(
"api_url" +
process.env.USER_KEY,
{
method: "POST",
headers: { "Content-Type": "application/json" },
}
)
.then(async (res) => {
return [await res.json(), res.status];
})
.then(([data, status]) => {
console.log(data);
if (data.steviloDelovnihMest > 0) {
let transporter = nodemailer.createTransport({
host: "host",
port: 25,
secure: false, // true for 465, false for other ports
});
let info = transporter.sendMail({
from: "<no-reply#text.com>", // sender address
to: user.email, // list of receivers
subject: `test`, // Subject line// plain text body
html: htmlbody, // html body
});
}
})
.catch((error) => {
return console.log(error);
});
});
console.log("Sending mails");
} catch (e) {
console.log(e);
}
});
};
function deleteEmptyProps(obj: any): any {
Object.keys(obj).forEach((k) => {
if (
!obj[k] ||
obj[k] === undefined ||
(Array.isArray(obj[k]) && obj[k].length === 0)
) {
delete obj[k];
}
});
return obj;
}
export const deletingNonActiveCRON = () => {
scheduleJob("0 * * * *", async () => {
try {
let response = await User.deleteNonActive();
console.log(response);
} catch (e) {
console.log(e);
}
});
};
And in my separate file mail.ts i have this:
module.exports.deleteNonActive = async function () {
let date = new Date();
return await User.deleteMany({
$and: [
{ dateStart: { $lt: new Date(date.setHours(date.getHours() - 48)) } },
{ aktivnost: { $eq: false } },
],
});
};
My idea is that I need also some deleteExpired function, something like that?
module.exports.deleteExpired = async function () {
await User.updateMany(
{
$and: [
{ dateEnd: { $lt: new Date() } },
{ aktivnost: { $eq: true } },
],
},
{ $set: { aktivnost: false } }
);
};
Which I also call in MailServiceCron.ts file like deleteNonActive function?

Related

Jest Mock Implementation is not working, instead original function is being called

I am trying to test an API by mocking the database function, but the imported function is being called instead of the mocked one.
Here are the code snippets
const supertest = require('supertest');
const axios = require('axios');
const querystring = require('querystring');
const { app } = require('../app');
const DEF = require('../Definition');
const tripDb = require('../database/trip');
const request = supertest.agent(app); // Agent can store cookies after login
const { logger } = require('../Log');
describe('trips route test', () => {
let token = '';
let companyId = '';
beforeAll(async (done) => {
// do something before anything else runs
logger('Jest starting!');
const body = {
username: process.env.EMAIL,
password: process.env.PASSWORD,
grant_type: 'password',
client_id: process.env.NODE_RESOURCE,
client_secret: process.env.NODE_SECRET,
};
const config = {
method: 'post',
url: `${process.env.AUTH_SERV_URL}/auth/realms/${process.env.REALM}/protocol/openid-connect/token`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify(body),
};
const res = await axios(config);
token = res.data.access_token;
done();
});
const shutdown = async () => {
await new Promise((resolve) => {
DEF.COM.RCLIENT.quit(() => {
logger('redis quit');
resolve();
});
});
// redis.quit() creates a thread to close the connection.
// We wait until all threads have been run once to ensure the connection closes.
await new Promise(resolve => setImmediate(resolve));
};
afterAll(() => shutdown());
test('post correct data', async (done) => {
const createTripMock = jest.spyOn(tripDb, 'addTrip').mockImplementation(() => Promise.resolve({
pk: `${companyId}_trip`,
uid: '1667561135293773',
lsi1: 'Kotha Yatra',
lsi2: companyId,
name: 'Kotha Yatra',
companyId,
origin: {
address: 'Goa, India',
location: {
lat: 15.2993265,
lng: 74.12399599999999,
},
},
destination: {
address: 'Norway',
location: {
lat: 60.47202399999999,
lng: 8.468945999999999,
},
},
path: [
{
lat: 15.2993265,
lng: 74.12399599999999,
},
{
lat: 60.47202399999999,
lng: 8.468945999999999,
},
],
isDeleted: false,
currentVersion: 1,
geofences: [],
}));
const response = await request.post('/api/trips').set('Authorization', `Bearer ${token}`).send(tripPayload);
expect(createTripMock).toHaveBeenCalled();
expect(response.status).toEqual(200);
expect(response.body.status).toBe('success');
done();
});
});
The database function:
const addTrip = (trip) => {
// const uid = trip.uid ? trip.uid : (Date.now() * 1000) + Math.round(Math.random() * 1000);
const uid = (Date.now() * 1000) + Math.round(Math.random() * 1000);
const item = {
pk: `${trip.companyId}_trip`,
uid: `v${trip.version ? trip.version : 0}#${uid}`,
lsi1: trip.name,
lsi2: trip.companyId,
name: trip.name,
companyId: trip.companyId,
origin: trip.origin,
destination: trip.destination,
path: trip.path,
isDeleted: false,
};
if (!trip.version || trip.version === 0) {
item.currentVersion = 1;
} else {
item.version = trip.version;
}
if (trip.geofences) item.geofences = trip.geofences;
const params = {
TableName: TN,
Item: item,
ConditionExpression: 'attribute_not_exists(uid)',
};
// console.log('params ', params);
return new Promise((resolve, reject) => {
ddb.put(params, (err, result) => {
// console.log('err ', err);
if (err) {
if (err.code === 'ConditionalCheckFailedException') return reject(new Error('Trip id or name already exists'));
return reject(err);
}
if (!trip.version || trip.version === 0) {
const newItem = { ...item };
delete newItem.currentVersion;
newItem.version = 1;
newItem.uid = `v1#${item.uid.split('#')[1]}`;
const newParams = {
TableName: TN,
Item: newItem,
ConditionExpression: 'attribute_not_exists(uid)',
};
// console.log('new params ', newParams);
ddb.put(newParams, (v1Err, v1Result) => {
// console.log('v1 err ', v1Err);
if (v1Err) return reject(v1Err);
item.uid = item.uid.split('#')[1];
return resolve(item);
});
} else {
item.uid = item.uid.split('#')[1];
return resolve(item);
}
});
});
};
module.exports = {
addTrip,
};
I was mocking the above database function when I was making a request to add API, instead, the original function is being called and I was getting the result that I had written in the mock Implementation.
What should I do to just mock the result ,when the function is called and no implementation of the original function should happen.
Even this did not give an error
expect(createTripMock).toHaveBeenCalled();
Still the database function call is happening
I tried using mockReturnValue, mockReturnValueOnce, mockImplemenationOnce but not luck.
Can anyone help me with this?

How to implement Gpay payment gateway in NodeJS?

I tried it in html and javascript it's working perfect in web (mobile's browser).I am using angular for frontend and node for backend but not getting any solution for redirect Playstore or Gpay for mobile browser. Basically I want to implement for mobile browser.
this is my node for backend code & for frontend I already paste static--
const canMakePaymentCache = 'canMakePaymentCache';
onBuyClicked();
function readSupportedInstruments() {
let formValue = {};
formValue['pa'] = keys.GPAY_MERCHANT_ID;//merchantId
formValue['pn'] = `Test_Gpay_Name`;//transactionId
formValue['tn'] = 'Testing Messages ';//message
formValue['mc'] = 'merchant Code';//
formValue['tr'] = 'Transaction Reference';
formValue['tid'] = 'Transaction id';
formValue['url'] = 'http://localhost.co/';
return formValue;
}
function readAmount() {
//const pay_amount = parseInt(req.body.amount) * 100;
return parseInt(req.body.amount) * 100;
}
function onBuyClicked() {
// if (!window.PaymentRequest) {
// console.log('Web payments are not supported in this browser.');
// return;
// }
let formValue = readSupportedInstruments();
const supportedInstruments = [
{
supportedMethods: ['https://pwp-server.appspot.com/pay-dev'],
data: formValue,
},
{
supportedMethods: ['https://tez.google.com/pay'],
data: formValue,
},
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: readAmount(),
},
},
displayItems: [
{
label: 'Original amount',
amount: {
currency: 'INR',
value: readAmount(),
},
},
],
};
const options = {
requestShipping: false,
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
shippingType: 'shipping',
};
let request = null;
try {
//const PaymentRequest = {};
//request = PaymentRequest(supportedInstruments, details, options);
request ={supportedInstruments, details, options};
} catch (e) {
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then((result) => {
showPaymentUI(request, result);
})
.catch((err) => {
console.log('Error calling checkCanMakePayment: ' + err);
});
}
function checkCanMakePayment(request) {
//if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
//return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
//}
var canMakePaymentPromise = Promise.resolve(true);
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
canMakePaymentCache = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}
function showPaymentUI(request, canMakePayment) {
if (!canMakePayment) {
redirectToPlayStore();
return;
}
let paymentTimeout = window.setTimeout(function () {
window.clearTimeout(paymentTimeout);
request.abort()
.then(function () {
console.log('Payment timed out after 20 minutes.');
})
.catch(function () {
console.log('Unable to abort, user is in the process of paying.');
});
}, 20 * 60 * 1000); /* 20 minutes */
request.show()
.then(function (instrument) {
window.clearTimeout(paymentTimeout);
processResponse(instrument); // Handle response from browser.
})
.catch(function (err) {
console.log(err);
});
}
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: instrumentString,
credentials: 'include',
})
.then(function (buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function (buyResultJson) {
completePayment(
instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function (err) {
console.log('Unable to process payment. ' + err);
});
}
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function () {
console.log('Payment completes.');
console.log(msg);
document.getElementById('inputSection').style.display = 'none'
document.getElementById('outputSection').style.display = 'block'
document.getElementById('response').innerHTML =
JSON.stringify(instrument, undefined, 2);
})
.catch(function (err) {
console.log(err);
});
}
console.log(`in line 448....`);
function redirectToPlayStore() {
//if (confirm('Tez not installed, go to play store and install?')) {
//window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha'
//res.writeHead( "https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha" );
const response_data = axios
.post(
'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha',
)
console.log(`in line no. 459... ${response_data}`);
return response_data;
//};
}
function instrumentToJsonString(instrument) {
var instrumentDictionary = {
methodName: instrument.methodName,
details: instrument.details,
shippingAddress: addressToJsonString(instrument.shippingAddress),
shippingOption: instrument.shippingOption,
payerName: instrument.payerName,
payerPhone: instrument.payerPhone,
payerEmail: instrument.payerEmail,
};
return JSON.stringify(instrumentDictionary, undefined, 2);
}

API Only sends 1 chunk of metadata when called

I have a problem with my API that sends metadata when called from my smart contract of website. Its NFT tokens and my database is postgres and API is node.js
The problem is when I mint 1 NFT metadata works perfect, but if I mint 2 or more it will only ever send 1 chunk of data? So only 1 NFT will mint properly and the rest with no data?
Do I need to set a loop function or delay? Does anyone have any experience with this?
Any help would be much appreciated.
Below is the code from the "controller" folder labeled "nft.js"
const models = require("../../models/index");
const path = require("path");
const fs = require("fs");
module.exports = {
create_nft: async (req, res, next) => {
try {
const dir = path.resolve(__dirname + `../../../data/traitsfinal.json`);
const readCards = fs.readFileSync(dir, "utf8");
const parsed = JSON.parse(readCards);
console.log("ya data ha final ??", parsed);
parsed.forEach(async (item) => {
// return res.json(item)
let newNft = await models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
});
});
return res.json({
data: "nft created",
error: null,
success: true,
});
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
get_nft: async (req, res, next) => {
try {
const { id } = req.params;
// console.log("id ?????????",id)
// console.log("type of ",typeof(id))
// const n=Number(id)
// console.log("type of ",typeof(id))
const nft = await models.NFT.findByPk(id);
if (!nft) {
throw new Error("Token ID invalid");
}
if (!nft.isMinted) {
throw new Error("Token not minted");
}
console.log(nft);
// }
const resObj = {
name: nft.name,
description: nft.description,
image: `https://gateway.pinata.cloud/ipfs/${nft.image}`,
attributes: [
{ trait_type: "background", value: `${nft.background}` },
{ trait_type: "body", value: `${nft.body}` },
{ trait_type: "mouth", value: `${nft.mouth}` },
{ trait_type: "eyes", value: `${nft.eyes}` },
{ trait_type: "tokenId", value: `${nft.tokenId}` },
{
display_type: "number",
trait_type: "Serial No.",
value: id,
max_value: 1000,
},
],
};
return res.json(resObj);
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
get_nft_all: async (req, res, next) => {
try {
// console.log("id ?????????",id)
// console.log("type of ",typeof(id))
// const n=Number(id)
// console.log("type of ",typeof(id))
const nft = await models.NFT.findAndCountAll({
limit: 10
});
// console.log(nft);
if (!nft) {
throw new Error("Token ID invalid");
}
// if (nft.isMinted) {
// throw new Error("Token not minted");
// }
// console.log(nft);
// }
var resObjarr = [];
for (var i = 0; i < nft.rows.length; i++) {
resObj = {
name: nft.rows[i].name,
description: nft.rows[i].description,
image: `https://gateway.pinata.cloud/ipfs/${nft.rows[i].image}`,
attributes: [
{ trait_type: "background", value: `${nft.rows[i].background}` },
{ trait_type: "body", value: `${nft.rows[i].body}` },
{ trait_type: "mouth", value: `${nft.rows[i].mouth}` },
{ trait_type: "eyes", value: `${nft.rows[i].eyes}` },
{ trait_type: "tokenId", value: `${nft.rows[i].tokenId}` },
{
display_type: "number",
trait_type: "Serial No.",
value: nft.rows[i].id,
max_value: 1000,
},
],
};
resObjarr.push(resObj);
}
console.log(JSON.stringify(resObjarr))
return res.json(resObjarr);
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
mint: async (req, res, next) => {
try {
const { id } = req.params;
const updated = await models.NFT.findByPk(id);
if (!updated) {
throw new Error("NFT ID invalid");
}
if (updated.isMinted) {
throw new Error("NFT Already minted");
}
updated.isMinted = true;
updated.save();
return res.json({
data: "Token minted successfully",
error: null,
success: true,
});
} catch (error) {
console.log("server error", error.message);
next(error);
}
},
};
Below is from the routes folder.
const router = require("express").Router();
const auth=require("../middleware/auth")
const {
create_nft,
get_nft,
get_nft_all,
mint
} = require("../controller/nft");
router.post(
"/create",
create_nft
);
router.get(
"/metadata/:id",
get_nft
);
router.get(
"/metadata",
get_nft_all
);
router.put(
"/mint/:id",
mint
);
module.exports = router;
Looking your code,you may having some kind of asyncrhonous issue in this part:
parsed.forEach(async (item) => {
// return res.json(item)
let newNft = await models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
});
});
Because .forEach is a function to be used in synchronous context and NFT.create returns a promise (that is async). So things happens out of order.
So one approach is to process the data first and then perform a batch operation using Promise.all.
const data = parsed.map(item => {
return models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
})
})
const results = await Promise.all(data)
The main difference here is Promise.all resolves the N promises NFT.create in an async context in paralell. But if you are careful about the number of concurrent metadata that data may be too big to process in parallel, then you can use an async iteration provided by bluebird's Promise.map library.
const Promise = require('bluebird')
const data = await Promise.map(parsed, item => {
return models.NFT.create({
name: item.Name,
description: item.Description,
background: item.Background,
body: item.Body,
mouth: item.Mouth,
eyes: item.Eyes,
head_gear: item.Head_Gear,
tokenId: item.tokenId,
image: item.imagesIPFS,
})
})
return data

How to mock AWS TimestreamWrite by jest

This project is to record data by AWS Timestream, and it works well.
However, I'm failed to mock AWS TimestreamWrite by using jest. I tried some ways but not working. Can someone help me?
My files as below:
ledger-service.js
const AWS = require("aws-sdk");
const enums = require("./enums");
var https = require("https");
var agent = new https.Agent({
maxSockets: 5000,
});
const tsClient = new AWS.TimestreamWrite({
maxRetries: 10,
httpOptions: {
timeout: 20000,
agent: agent,
},
});
module.exports = {
log: async function (audit) {
try {
if (Object.keys(audit).length !== 0) {
if (!isPresent(audit, "name")) {
throw new Error("Name shouldn't be empty");
}
if (!isPresent(audit, "value")) {
throw new Error("Value shouldn't be empty");
}
return await writeRecords(recordParams(audit));
} else {
throw new Error("Audit object is empty");
}
} catch (e) {
throw new Error(e);
}
},
};
function isPresent(obj, key) {
return obj[key] != undefined && obj[key] != null && obj[key] != "";
}
function recordParams(audit) {
const currentTime = Date.now().toString(); // Unix time in milliseconds
const dimensions = [
// { Name: "client", Value: audit["clientId"] },
{ Name: "user", Value: audit["userId"] },
{ Name: "entity", Value: audit["entity"] },
{ Name: "action", Value: audit["action"] },
{ Name: "info", Value: audit["info"] },
];
return {
Dimensions: dimensions,
MeasureName: audit["name"],
MeasureValue: audit["value"],
MeasureValueType: "VARCHAR",
Time: currentTime.toString(),
};
}
function writeRecords(records) {
try {
const params = {
DatabaseName: enums.AUDIT_DB,
TableName: enums.AUDIT_TABLE,
Records: [records],
};
return tsClient.writeRecords(params).promise();
} catch (e) {
throw new Error(e);
}
}
ledger-service.spec.js
const AWS = require("aws-sdk");
const audit = require("./ledger-service");
describe("ledger-service", () => {
beforeEach(async () => {
jest.resetModules();
});
afterEach(async () => {
jest.resetAllMocks();
});
it("It should write records when all success", async () => {
const mockAudit={
name: 'testName',
value: 'testValue',
userId: 'testUserId',
entity: 'testEntity',
action: 'testAction',
info: 'testInfo',
};
const mockWriteRecords = jest.fn(() =>{
console.log('mock success')
return { promise: ()=> Promise.resolve()}
});
const mockTsClient={
writeRecords: mockWriteRecords
}
jest.spyOn(AWS,'TimestreamWrite');
AWS.TimestreamWrite.mockImplementation(()=>mockTsClient);
//a=new AWS.TimestreamWrite();
//a.writeRecords(); //these two lines will pass the test and print "mock success"
await audit.log(mockAudit); //this line will show "ConfigError: Missing region in config"
expect(mockWriteRecords).toHaveBeenCalled();
});
});
I just think the the AWS I mocked doesn't pass into the ledger-service.js. Is there a way to fix that?
Thanks
updates: Taking hoangdv's suggestion
I am thinking jest.resetModules(); jest.resetAllMocks(); don't work. If I put the "It should write records when all success" as the first test, it will pass the test. However, it will fail if there is one before it.
Pass
it("It should write records when all success", async () => {
const mockAudit = {
name: 'testName',
value: 'testValue',
userId: 'testUserId',
entity: 'testEntity',
action: 'testAction',
info: 'testInfo',
};
await audit.log(mockAudit);
expect(AWS.TimestreamWrite).toHaveBeenCalledWith({
maxRetries: 10,
httpOptions: {
timeout: 20000,
agent: expect.any(Object),
},
});
expect(mockWriteRecords).toHaveBeenCalled();
});
it("It should throw error when audit is empty", async () => {
const mockAudit = {};
await expect(audit.log(mockAudit)).rejects.toThrow(`Audit object is empty`);
});
Failed
it("It should throw error when audit is empty", async () => {
const mockAudit = {};
await expect(audit.log(mockAudit)).rejects.toThrow(`Audit object is empty`);
});
it("It should write records when all success", async () => {
const mockAudit = {
name: 'testName',
value: 'testValue',
userId: 'testUserId',
entity: 'testEntity',
action: 'testAction',
info: 'testInfo',
};
await audit.log(mockAudit);
expect(AWS.TimestreamWrite).toHaveBeenCalledWith({
maxRetries: 10,
httpOptions: {
timeout: 20000,
agent: expect.any(Object),
},
});
expect(mockWriteRecords).toHaveBeenCalled();
});
In ledger-service.js you call new AWS.TimestreamWrite "before" module.exports, this means it will be called with actual logic instead of mock.
The solution is just mock AWS before you call require("./ledger-service");
ledger-service.spec.js
const AWS = require("aws-sdk");
describe("ledger-service", () => {
let audit;
let mockWriteRecords;
beforeEach(() => {
mockWriteRecords = jest.fn(() => {
return { promise: () => Promise.resolve() }
});
jest.spyOn(AWS, 'TimestreamWrite');
AWS.TimestreamWrite.mockImplementation(() => ({
writeRecords: mockWriteRecords
}));
audit = require("./ledger-service"); // this line
});
afterEach(() => {
jest.resetModules(); // reset module to update change for each require call
jest.resetAllMocks();
});
it("It should write records when all success", async () => {
const mockAudit = {
name: 'testName',
value: 'testValue',
userId: 'testUserId',
entity: 'testEntity',
action: 'testAction',
info: 'testInfo',
};
await audit.log(mockAudit);
expect(AWS.TimestreamWrite).toHaveBeenCalledWith({
maxRetries: 10,
httpOptions: {
timeout: 20000,
agent: expect.any(Object),
},
});
expect(mockWriteRecords).toHaveBeenCalled();
});
});

Angular 4 Getting 404 not found in production mode

I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.

Resources