Pass variable with generated password from backend into frontend - javascript

I am trying to pass my variable with generated password into my front-end side.
I think that my main problem is that I am generating password inside
route.post
this is my piece of fileUpload.route.ts
router.post('/upload-file', upload.array('file', 6), (req:any, res:any, next:any) => {
//...
genPass();
}
Inside genPass() is
let password = generator.generate({
length: 10,
numbers: true
});
I tried to do
module.exports = router, genPass;
and
router.get('/getpassword', fileController.fileGeneratedPassword);
Then inside my Controller
const password = require('../routes/fileUpload.route');
class FileController {
public async fileGeneratedPassword(req: Request, res: Response): Promise<void> {
console.log('pass: ' + JSON.stringify(password));
res.json(password);
}
}
But console.log is always empty.
How should I pass this variable?
I think that I must generate password inside router.post because when I upload in my frontend file then I want to generate password at the same time to "encrypt file".
I want to display generated password in my Angular frontend

module.exports returns a single value.
you can return an object if you like but I'd separate them into 2 files
generator
function genPass() {
return generator.generate({
length: 10,
numbers: true
});
}
module.exports = genPass
controller
const genPass = require('generator');
class FileController {
public async fileGeneratedPassword(req: Request, res: Response): Promise<void> {
const password = genPass()
console.log('pass: ' + JSON.stringify(password));
res.json(password);
}
}

Related

Property 'email' does not exist on type 'string'

I am very new to typescrypt, and I'm currently in the process of migrating a project from JS to TS.
While I was changing some things on my server endpoints, an error appeared:
Property 'email' does not exist on type 'string | JwtPayload'
This is my code so far:
try {
const token = await TokenController.getTokenFromRequest(req);
const decoded = jwt.decode(token);
const user = await AuthController.getUserByMail(decoded.username); // <- Error appears here
res.json(user);
} catch (error: any) {
ErrorController.errorCallback(error, res);
}
Edit: My code for 'getUserByMail' looks like so:
static async getUserByMail(email: string, includePassword = false) {
let query = User.findOne({
email: email
});
if (!includePassword) {
query.select('-password');
}
return query.exec();
}
I know that the error happens because I'm trying to access a property that string doesn't have. Any suggestions?
Create global.d.ts:
// global.d.ts
declare module "jsonwebtoken" {
export interface JwtPayload {
//make optional so when you try to decode stuff other than user it will show it can be undefined
email?: string;
}
}

What design pattern to use when object create multiple time and share to different file?

enter code hereI have case i needs 2 connector MongoClient. first client to connect to local mongodb server. 2nd client to connect to remote mongodb. 2 client inside 1 file database-connector.js. is it right or wrong in this ways? what the correct ways in this problem?
class CatchError {
static error: string | unknown;
static save(error: string | unknown) {
this.error = error;
const re = new RegExp('ECONNREFUSED', 'i')
if (re.test(error.message)) {
// fs.write('system.error.log')
}
}
}
class DBClient {
client: MongoClient;
constructor(url: string, config: Partial<MongoClientOptions>) {
this.client = new MongoClient(url, config)
}
async connect() {
try {
this.client = await this.client.connect();
return this.client;
} catch(error) {
CatchError.parse(error)
}
}
}
// for entire data application
export const localDBClient = initializeDBConnection("mongodb://localhost");
// only for authentication to access application
export const remoteDBClient = initializeDBConnection("mongodb+srv://se132.aws-slcuster.com");
gui.js
import { remoteDBClient } from "database-connector.js";
// use client //
model.js
import { localDBClient } from "database-connector.js";
// use client //

TypeScript this keyword context error - undefined

I have a aws lambda written in JS (TypeScript) which calls functions from different classes. I am getting undefined for the existingproducts variable even though it works fine when the REACT UI sends a call to the function. Below is my code using this keyword to reference the method of other class with current object in scope.
Entry point for the lambda
export const handler = async (upload: FileUpload, context: Context) => {
.....code .....
const parser = new ExcelValidator(new LookupService(), new ProductService());
const status = await parser.performExistingUpcValidation(products as Product[], upload, workbook);
return status
PerformExisitingUPCValidation
export class ExcelValidator {
constructor(public lookupService: LookupService, public productService: ProductService) {
}
async performExistingUpcValidation(products: Product[], upload: FileUpload, workbook?: Workbook): Promise<FileStatus> {
...code...
const existingProducts: any[] = await this.productService.getExistingProductsByUpcOrProductCode(productUpcs, productCodes);
console.log("This is the exisitingProduct", existingProducts)
}
ProductServiceClass
export class ProductService {
constructor() {
}
#Query(()=>[Product])
async getExistingProductsByUpcOrProductCode(#Arg("upcs", ()=> [String]) upcs: string[], #Arg("productCodes", ()=> [String]) productCodes: string[]): Promise<Product[]> {
console.log("I came here")
let query = `SELECT * from table
in (${upcs.join(",")})`;
if(productCodes.length){
query += ` OR "productCode" in ('${productCodes.join("','")}')`;
}
const results = await pool.snowflake?.execute(query);
return results as Product[];
}
After all the execution I am able to see
This is the exisitingProduct undefined
which means my execution does not reach the ProductServiceClass. Can someone point me to what is wrong or missing? Also any documentation/reference to read more will help alot.
My suggestion for you is review the item below:
const results = await pool.snowflake?.execute(query);
Are you confident that snowflake is not null, because you are accepting to be undefined with help of the question mark.

How to correctly return from function

How to correctly return apiKey from User.ts createUser function to Test.ts in my case?
User.ts
interface User {
url: string,
name: string,
}
class User{
async createUser(
user: User
):Promise<void> {
let apiKey = await user.getUserApiKey(user.name);
console.log(`${user.name} api key - ${apiKey} received`);
return apiKey;
}
}
Test.ts
test("Smoke Test", async (t) => {
console.log(${apiKey} - User api key)
}
You may have to specify Promise<void> to the correct type of apiKey.
It may look like Promise<String>, or leave the return type specification empty (i.e. remove the : Promise<void> from the createUser method).
In the Test.ts you have to create a User object first and call the createUser Method on this object.
test("Smoke Test", async (t) => {
let user = new User();
user.name = "theName";
user.url = "theURL";
let apiKey = await user.createUser(user);
console.log(${apiKey} - User api key)
}
It seems like, the createUser method is not well designed. Is it intentional to have a (possible different) user parameter, although it is called on a user object?

How to tell typescript req.user in Passport JS never will be undefined?

When using Passport JS, the req.user inside the route, is treated as possible undefined. But the middleware before my route method is making sure that this isn't the case. How to tell that to typescript?
Object is possibly 'undefined'.
Example:
someMethod = async (req: Request, res: Response) => {
const { user } = req
const userId: number = user.id
}
In the above typescript throw an error because user.id is possibly undefined.
I sure could do something like this:
if (!user) return
const userId: number = user.id
But I believe that repeating this piece of code over and over through my methods is not the best approach because middleware is already doing that before even reach the route method.
I suggest you to to simply declare global Express namespace with params that you need like that:
declare global {
namespace Express {
interface Request {
user: User //or other type you would like to use
}
}
}
After that you will be able to user req.user without //#ts-ignoreor optional chaining.
someMethod = async (req: Request, res: Response) => {
const { user } = req
const userId: number = user.id //user will be defined
}

Categories