Swagger-codegen: error: ignored arguments: 'Object' - javascript

I'm getting a weird error, and I can't seem to google the right things, as I'm finding no help online. I am writing a script that converts swagger files to typescript. The error message is the one in the title, and sadly that's all the information I have. I will post the code below, and the part where (I believe) the message is coming from:
async function getJson(){
const agent = new https.Agent({
rejectUnauthorized: false
});
return axios.get('https://common-customer-bpms.dev.havida.net/v3/api-docs', { httpsAgent: agent })
.then(response => generateSwagger(response))
}
getJson();
async function generateSwagger(response) {
try {
execSync(`java -jar ..\\swagger-codegen-cli.jar generate -l typescript-angular -o .\\projects\\common\\src -i ${response}`);
} catch (error){
console.log(error);
console.log('You must have Java installed! You may have to change JAVA_HOME location & path (Ex: set JAVA_HOME=`C:\\Programme\\Java\\jre1.8.0_321`), (set PATH=${JAVA_HOME}/bin:$PATH)')
}
}
I think the error is coming from the try block, the very last argument (-i ${response}). Am I able to use the parameter of the function in this way, or can I only use strings in cli commands? I'm at a loss

After multiple days of trying, here is the full code that works for anyone who may need it:
import axios from 'axios';
import https from 'node:https';
import {execSync} from 'child_process';
import fs from 'fs/promises';
async function getJson(){
const agent = new https.Agent({
rejectUnauthorized: false
});
return axios.get('https://common-customer-bpms.dev.havida.net/v3/api-docs', { httpsAgent: agent })
.then(response => fs.writeFile("temp.json", JSON.stringify(response.data), (error)=>{console.log(error)}))
.then(() => generateSwagger())
}
getJson();
async function generateSwagger() {
try {
execSync(`java -jar ..\\swagger-codegen-cli.jar generate -l typescript-angular -i temp.json -o .\\projects\\common\\src\\lib`);
} catch (error){
console.log(error);
console.log('You must have Java installed! You may have to change JAVA_HOME location & path (Ex: set JAVA_HOME=`C:\\Programme\\Java\\jre1.8.0_321`), (set PATH=${JAVA_HOME}/bin:$PATH)')
} finally {
fs.unlink("temp.json");
}
}
This pulls the json from the desired url, and writes it to a file. This file is then used as the destination for -i, and once the conversion is complete, the json is deleted in the finally block.

Related

How to get the current module's file path in a node module?

I want to print the correct filepath even if the function is imported in some other module inorder to handle the errors correctly. How can I do that? I am using serverless stack.
Please refer the following code,
class Logger {
filePath: string;
constructor(fp: string) {
filePath = fp;
}
printLog(info) {
const { timestamp, message } = info;
return `${timestamp} ${filePath}: ${message}`;
}
}
This is used in dbConnection.ts as,
const logger = new Logger(__filename);
export const connectToDB = () => {
try {
//DB connection code.
} catch(error) {
logger.print({ timestamp: new Date().toISOString(), message: error.message });
}
};
Now, I want to connect to db from some other module lets say, test.ts then I will use it as follows,
export const test = () => {
//some code here...
connectToDB();
}
When there occurs an error while connecting to DB, then It prints something like this,
2022-05-27T05:24:47.548Z src/test.ts: Error in connecting DB url is unreachable please check your internet connection.
In order to have proper debuggability, I want to print the filename from where the exception is actually thrown. That is src/dbConnection.ts and not src/test.ts.
Try using
__filename
__filename: This will return the path of the file executing
__dirname: This will return the path of the directory in which the file executing is located.
Check if it does what you need like
console.log(__filename);
Try to change filePath to this.filePath in your Logger Class

How to use google recaptcha in nuxt?

I am using nuxt and would like to use this library: https://github.com/nuxt-community/recaptcha-module. But I don't understand how to verify that the user has passed the check. The example doesn't tell me too much (https://github.com/nuxt-community/recaptcha-module/blob/master/example/v3/pages/index.vue). Could someone show me how to do it correctly?
This example is only half the story. It returns a Recaptcha V3 token on the client-side.
This must then be sent to the serverside and verified using your secret key.
This is done by sending a post to this URL:
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${token}`;
You do not want to allow this secret key on the client side.
To achieve this in Nuxt, assuming version 2.13+, you can utilise privateRuntimeConfig in your nuxt config.
This will allow you to link a .env file to be injected only on the server side.
For this use case, a privateRuntimeConfig like this should suffice:
privateRuntimeConfig: {
secretKey: process.env.GOOGLE_SECRET
}
Once you have done this, you will be able to access these variables as part of this.$config within your Nuxt application - in this case this.$config.secretKey when calling the Recaptcha verify endpoint.
For more information check out the Nuxt blog
Use https://github.com/nuxt-community/recaptcha-module, in your nuxt.config.js
modules: [
'#nuxtjs/recaptcha',
],
recaptcha: {
hideBadge: true,
siteKey: "ABC...", // Better would be from 'process.env.API_KEY' and with '.env' file
version: 2, // Or 3
},
Keep in mind that modules, that's not the same as buildModules (sometimes it might confuse due to similar naming).
Here is a working implementation for ReCaptcha V3:
package.json
"dependencies": {
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/recaptcha": "^1.0.4",
"h3": "^0.3.9",
},
Note the h3 version. I wasn't able to get it working with a newer version of that because the library is converted to EJS/mjs and TypeScript, which conflicts with Nuxt. Transpiling h3 didn't fix it. It may work with Nuxt V3+.
nuxt.config.js
modules: [
['#nuxtjs/recaptcha', {
siteKey: process.env.RECAPTCHA_SITE_KEY,
version: 3,
}],
],
serverMiddleware: [
{ path: '/api/check-token', handler: '~/middleware/recaptcha' },
],
middleware/recaptcha.js
import { useBody } from 'h3';
import axios from 'axios';
export default async (req, res) => {
res.setHeader('Content-Type', 'application/json');
try {
const { token } = await useBody(req);
if (!token) {
res.end(
JSON.stringify({
success: false,
message: 'Invalid token'
})
);
return;
}
axios.get(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`).then((answer) => {
if (answer.status) {
res.end(
JSON.stringify({
success: true,
message: 'Token verified'
})
);
} else {
res.end(
JSON.stringify({
success: false,
message: 'Invalid token'
})
);
}
});
} catch (e) {
console.log('ReCaptcha error:', e);
res.end(
JSON.stringify({
success: false,
message: 'Internal error'
})
);
}
};
.env
RECAPTCHA_SITE_KEY=gosei478htosvei478tvoei478tvge
RECAPTCHA_SECRET_KEY=ios47eos487t6es4897gtv6es487
index.vue
async mounted() {
try {
await this.$recaptcha.init();
} catch (err) {
throw new Error(`index# Problem initializing ReCaptcha: ${err}.`);
}
},
beforeDestroy() {
this.$recaptcha.destroy();
},
methods: {
async submitContactForm() {
try {
const token = await this.$recaptcha.execute('contact')
const formData = {
email: this.contactForm.email,
firstname: name.firstName,
lastname: name.lastName,
phone: this.contactForm.phone,
band_name: this.contactForm.band_name,
initial_message: this.contactForm.message,
}
// note: use POST request
const recaptcha = await this.$axios.post('/api/check-token', { token });
console.log('recaptcha', recaptcha.data);
if (recaptcha.data.success) {
const result = await this.$axios.post(process.env.CONTACT_FORM_API, formData);
// cleanup logic
} else {
// handle error case
}
} catch (err) {
// handle errors
}
},
},
You can read more here: https://www.npmjs.com/package/#nuxtjs/recaptcha
Note the section where it says
Server Side
When you send data + token to the server, you should verify the token on the server side to make sure it does not requested from a bot. You can find out how to verify token on the server side by looking at the server middleware inside v2 example. (The server side is same for both versions)
The above server-side middleware comes from there. It is important to use the version of h3 that I suggest because you need it to access useBody(req). I tried for several hours to find another way to read the request body but it proved too difficult. Your results may vary in a newer version of Nuxt. I suggest trying the newest version of h3 and if that fails with errors when building the application, try the older version.
It is critically important to not expose the ReCaptcha secret key, and this solution keeps it secret in the server-side.
A more optimal solution might be to use your actual server and make an endpoint for validating ReCaptcha tokens. This above solution allows you to do it purely client-side, assuming you are using SSR.

How can I load environment variables with ts-node?

I've tried a few implementations which none have been successful.
First Attempt
Using eval in package.json script "fetch:data": "eval $(cat .env) ts-node -O '{\"module\":\"commonjs\"}' ./bin/build-api-data.ts".
This results in a JSON parsing error because eval is removing my quotes for some reason.
undefined:1
{module:commonjs}
^
SyntaxError: Unexpected token m in JSON at position 1
Second Attempt
Using dotenv, the problem I encountered here was it was a race condition resulting in errors like this:
$ CANDID_ENV=local ts-node -O '{"module":"commonjs"}' ./bin/build-api-data.ts
/Users/lassiter.gregg/code/candidco-web/node_modules/contentful/dist/webpack:/contentful/contentful.js:49
throw new TypeError('Expected parameter accessToken')
^
TypeError: Expected parameter accessToken
Code Sample
import fs from 'fs';
import path from 'path';
import fetchApiData from '../lib/apiData';
import dotEnv from 'dotenv-safe';
const { CANDID_ENV } = process.env;
const isLocalBuild = CANDID_ENV === 'local';
console.log(dotEnv);
const API_DATA_FILENAME = 'api_data.json';
const ensureDirectoryExistence = filePath => {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
};
const writeData = (filename, data) => {
const filePath = path.join(__dirname, '..', '.data', filename);
ensureDirectoryExistence(filePath);
fs.writeFileSync(filePath, JSON.stringify(data));
console.log('API data stored', filePath);
};
const fetchAndStoreApiData = async () => {
console.log('Fetching all API data');
await dotEnv.config({
path: isLocalBuild ? './.env' : `./.env.${CANDID_ENV}`,
});
const newData = await fetchApiData();
writeData(API_DATA_FILENAME, newData);
};
const init = async () => {
fetchAndStoreApiData();
};
if (require.main === module) {
init();
}
In the case above, I've tried doing dotenv.config at the top of the file, in the init, in the function as you see. It always throws the same error about contentful not getting the env variable it needs. That said, if I log process.env and comment out the code relevant to fetchApiData then I see all my environment variables. That's why I think it's a race-time condition but haven't been able to find anything similar to my own issue.
Additionally, what makes this even more thorny is that this is a custom script that has to work in a node and esnext environment. So, I've had my fair share of thorny import/export issues using syntax I don't really prefer but haven't found away around it (e.g. export = someFunction).
Do I see it correctly, that you are trying to configure dotenv with a variable that you initialize with an env variable? I don't think that's going to work out.
Dotenv's work is to load the env variables to process.env. You have to config it as early as possible in your app.
More about it here: https://www.npmjs.com/package/dotenv

error sending request for url (https://deno.land/std/encoding/csv.ts) (os error 10013)

Unable to import the stdlib files from deno.land to local cache on running mod.ts.
error: error sending request for url (https://deno.land/std/encoding/csv.ts): error trying to connect: tcp connect error: An attempt was made to access
a socket in a way forbidden by its access permissions. (os error 10013)
Imported from "file:///C:/Current_Tasks/Deno/Kepler/mod.ts:3"
Is there anything additional that needs to be enabled to import these files?
import { join } from "https://deno.land/std/path/mod.ts";
import { BufReader } from "https://deno.land/std/io/bufio.ts";
import { parse } from "https://deno.land/std/encoding/csv.ts";
async function loadPlanetsData() {
const path = join(".", "test.csv");
const file = await Deno.open(path);
const bufReader = new BufReader(file);
const result = await parse(bufReader, {
header: true,
comment: "#",
});
Deno.close(file.rid);
console.log(result);
}
await loadPlanetsData();
Update: Used
deno run --allow-read mod.ts
import { join } from "https://deno.land/std/path/mod.ts";
import { BufReader } from "https://deno.land/std/io/bufio.ts";
import { parse } from "https://deno.land/std/encoding/csv.ts";
async function loadPlanetsData() {
const path = join(".", "test.csv");
const file = await Deno.open(path);
const bufReader = new BufReader(file);
const result = await parse(bufReader, {
header: true,
comment: "#",
});
Deno.close(file.rid);
console.log(result);
}
await loadPlanetsData();
While running this file you need to give read access to the Deno.
Deno is secure by default. Therefore, unless you specifically enable it, a deno module has no file, network, or environment access for example. Access to security sensitive areas or functions requires the use of permissions to be granted to a deno process on the command line.
For the following example, mod.ts has been granted read-only access to the file system. It cannot write to it, or perform any other security sensitive functions.
deno run --allow-read mod.ts

How to fix 'find' command in windows terminal

I wrote a Nodejs script which finds the last changed/modified file names.
For that reason, I am using find CLI command. I have one hidden file .change to compare other files to that one (modified times).
Here is a code below:
const es6dir = 'es6';
const path2dir = './htdocs/';
const exec = require("child_process").exec;
exec(`find ${path2dir + es6dir}/ -type f -newer .change`, (error, stdout) => {
if(error){
console.log(`Error: ${error}`);
return;
}
console.log(stdout);
//update .change modified timestamp
exec('touch -c .change');
}
Everything works fine if I run this command in Git Bash but if I use windows terminal it says an incorrect command.
Is there a simple way which will work for Linux and Windows terminal at the same time?
I would like to run this command in both platforms because some of the team members are working on Linux while others are using windows machines.
Consider using Node's built-in fs.Stats over platform specific commands or utilities. The fs module exposing fs.stat method returns the property mtime comprising last modified time in milliseconds.
Cross compatibility can be achieved through child processes or using fs.stat and fs.writeFile.
Stats returns an object like such:
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 5077219,
size: 11,
blocks: 8,
atimeMs: 1556271390822.264,
mtimeMs: 1556271389892.5886,
ctimeMs: 1556271389892.5886,
birthtimeMs: 1556270439285.706,
atime: 2019-04-26T09:36:30.822Z,
mtime: 2019-04-26T09:36:29.893Z,
ctime: 2019-04-26T09:36:29.893Z,
birthtime: 2019-04-26T09:20:39.286Z }
As suggested in comments and an answer, I agree this would be a better approach. Here is how you can approach creating a new file, and checking creation date.
const fs = require('fs');
// Directory
const PATH = './';
// Get file's stats
fs.stat(`./.change`, function(error, stats) {
if (error) { throw error; } // Throw if an error, file not found
let time = Date.now(); // Current Time
console.log(`Current .change: Created: `, stats['mtime']); // Created Time
// If current time > file creation time
if (time > stats['mtime']) {
// writeFile function with filename, content and callback function
fs.writeFile(`${PATH}/.change`, 'Inside File', function (error) {
if (error) { throw error; }
console.log('File is updated successfully.');
});
}
});

Categories