Not able register hapi-cron-job plugin - javascript

I am trying to schedule cronjobs which will run at specified time, i am using hapi-cron-job of hapi, when i try to register the plugin, i am getting below error.
[1] "plugin.register" must be of type function
at Object.exports.apply (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\config.js:19:15)
at internals.Server.register (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\server.js:454:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Please find the configuration while registering the plugin.
server.js
const { plugins } = require('./register/index');
await server
.register(plugins)
.then(() => {})
.catch(err => {
console.error('Plugin registeration failed!');
console.error(err);
});
index.js
module.exports.plugins = [
// I have here other pluguns, passing this array for registration in server.js
require("./hapi-cron-job-plugin")
];
hapi-cron-job-plugin.js
const hapiCronJob = require('hapi-cron-job')
const plugin = {
register: require('hapi-cron-job'),
options: {
jobs: [
{
name: "diplay time",
enabled: true,
immediate: true,
schedule: "every 1 s",
execute: alertSystemAdminAndDispatcher,
environments: ['development', 'staging']
}
],
}
}
module.exports = plugin;
nodeJS version: v14.17.3
Hapi-cron-job: "hapi-cron-job": "^2.0.1"

Related

How to trigger cypress after:run after tests finish execution

I'm using cypress + multiple-cucumber-html-report to generate a report after execution. There is the possibility to add custom data to the report such as execution start and end time.
I assume this information somehow comes from cypress as part of the result meta data.
I tried to put results in json file after the run finishes, by adding it to the cypress config file:
import { defineConfig } from 'cypress';
import * as fs from 'fs';
async function setupNodeEvents(on, config) {
on('after:run', async (results) => {
if (results) {
fs.mkdirSync("cypress/.run", { recursive: true });
fs.writeFile("cypress/.run/results.json", JSON.stringify(results), (err) => {
if (err)
console.log(err);
else {
console.log("Successful results has been written");
}
});
}
})
return config;
}
export default defineConfig({
e2e: {
setupNodeEvents,
experimentalInteractiveRunEvents: true
},
});
then read these results in the report generation file:
const report = require('multiple-cucumber-html-reporter');
const fs = require('fs');
fs.readFile('cypress/.run/results.json', function read(err, data) {
if (err) {
throw err;
}
var runInfos = JSON.parse(data);
report.generate({
jsonDir: './cypress/result/',
reportPath: './cypress/report/',
metadata:{
browser: {
name: runInfos.browserName,
version: runInfos.browserVersion
},
device: 'Cypress',
platform: {
name: mapOs(runInfos.osName)
}
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'project'},
{label: 'Execution Start Time', value: new Date(runInfos.startedTestsAt).toLocaleString()},
{label: 'Execution End Time', value: new Date(runInfos.endedTestsAt).toLocaleString()}
]
}
});
});
unfortunately the after:run was never triggered, and not even throwing an error.
Take a look at the docs on After Run API
When running via cypress open, the after:run event only fires if the experimentalInteractiveRunEvents flag is enabled.
Unfortunately, from the look of your config sample you must be using an older version of Cypress (pre v10).
To make this more useful, upgrade Cypress the use the flag mentioned above like this:
// cypress.config.js
const { defineConfig } = require('cypress')
module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('after:run', (results) => {
/* ... */
})
},
experimentalInteractiveRunEvents: true, // here is the flag, not documented in the configuration page
},
})

Using console log in Knex migration not logging

My issue: The console.log('tableNobject: ', tableNobject) does not log in knex migration.
The following code is what I have tried:
// solution A
export async function up(knex: Knex) {
const tableAobject = await knex.select('*').from('tableAobject');
console.log('tableAobject: ', tableAobject);
}
// solution B
export async function up(knex: Knex) {
await knex.select('*').from('tableBobject').then((tableBobject) => {
console.log('tableBobject: ', tableBobject);
});
}
However my terminal output is the following:
Migration Starting ...
Migrated
Migration Done.
These logs come from our migration script where we call database.migrate.latest()
My expected terminal output for the code above would be something like this:
Migration Starting ...
tableNobject: [
{
id: 'randomId'
someData: 'someDataString'
...
},
...
]
Migrated
Migration Done.
I know logging tables that you get from knex is possible because when I set up a test script outside the migration flow I can log the table without issues.
I have tried the following addition of settings:
const configA = {
...
debug: true,
}
const configB = {
...
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
}
const configC = {
...
debug: true,
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
};
The different settings above dont give me the logging in the terminal as I want.
The base settings (I dont know if this gives an added value):
const config = {
client: 'postgresql',
connection: {
host: '127.0.0.1',
port: '5432',
database: 'projectName_develop',
user: 'user',
password: 'dev',
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
directory: path.join(__dirname, 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'seeds'),
},
asyncStackTraces: true,
};
So the reason why my console.log didnt log was because the migrations are TypeScript files.
I forgot to run the command: npm run build-ts-backed:watch
So the solution was easier than the issue at hand. Please remember to run your TypeScript compiler when you test in TypeScript.

Issue with Cypress.js and uncaught exceptions

I'm very new to Cypress.js.
Problem statement:
I'm running cypress in headless mode (Chrome) and one of the API calls is failing with uncaught exception. However, when I manually visit the url it works fine!
I'm not sure if its because of some SSL certificate issue or what's happening. Everything works normally when I visit the url in my chrome/firefox/safari.
Follow-up questions:
My recording shows it's uncaught exception but I don't know why / what is failing.
How do I log my failing network requests into a log file to see what the actual error is?
Am I missing any configuration?
This is my configuration:
cypress/plugins/index.js
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('before:browser:launch', (browser = {}, launchOptions) => {
launchOptions.args.push('--ignore-urlfetcher-cert-requests')
launchOptions.args.push(`--ignore-certificate-errors`)
launchOptions.args.push(`--unsafely-treat-insecure-origin-as-secure=http://localhost:9999`)
return launchOptions
})
}
Cypress.json
{
"reporter": "junit",
"reporterOptions": {
"mochaFile": "cypress/results/helltool.xml",
"toConsole": true
},
"defaultCommandTimeout": 20000,
"pageLoadTimeout": 20000,
"responseTimeout": 20000,
"chromeWebSecurity": false
}
Sample Test
Cypress.on('uncaught:exception', (err, runnable) => {
console.log(`CYPRESS uncaught exception FLOW:::: ${err}`);
debugger;
return false;
});
describe('Flow Sanity Tests', () => {
before(() => {
// We need to login before we can do anything
// TODO: Abstract this inside Looker.explore
cy.login('admin', { flow: true })
})
it('Test to check Flow exists and run it', () => {
// Some test to execute after login
})
Login flow (in support/commands.js)
Cypress.Commands.add('login', (userType, options = {}) => {
const types = {
admin: {
email: 'demo#demo',
password: 'thisisademopassword',
},
}
// Go to login page
cy.goTo('login', options)
// grab the user
const { email, password } = types[userType]
cy.wait(2000)
// type the stuff.
cy.get('#login-email', { timeout: 30000 }).should('exist').debug()
cy.get('#login-email').type(email)
cy.get('#login-password').type(password)
cy.get('#login-submit').click()
})
Execution:
npm run cypress:run -- --spec "cypress/integration/flow/demo.spec.js"
--browser chrome

Module not found: Can't resolve 'child_process' - google-spreadsheet

I am trying to save form data to a spreadsheet in Next.js but I keep getting this error which appears as soon as I import google-spreadsheet
Error
./node_modules/google-spreadsheet/node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'
Bellow is what I have that is causing the error.
// The error appears when I do this import
import { GoogleSpreadsheet } from "google-spreadsheet";
const SPREADSHEET_ID = process.env.NEXT_PUBLIC_SPREADSHEET_ID;
const SHEET_ID = process.env.NEXT_PUBLIC_SHEET_ID;
const CLIENT_EMAIL = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL;
const PRIVATE_KEY = process.env.NEXT_PUBLIC_GOOGLE_SERVICE_PRIVATE_KEY;
const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
const appendSpreadsheet = async (row) => {
try {
await doc.useServiceAccountAuth({
client_email: CLIENT_EMAIL,
private_key: PRIVATE_KEY,
});
// loads document properties and worksheets
await doc.loadInfo();
const sheet = doc.sheetsById[SHEET_ID];
const result = await sheet.addRow(row);
return result;
} catch (e) {
console.error("Error: ", e);
}
};
I just solve it.
Please create next.config.js file in your root.
And fill it below.
module.exports = {
webpack: config => {
config.node = {
fs: 'empty',
child_process: 'empty',
net: 'empty',
dns: 'empty',
tls: 'empty',
};
return config;
},
};
Hoorai!
I was having this problem with nextjs 12. Here's what fixed it for me:
My code:
const doc = new GoogleSpreadsheet(SPREADSHEET_ID);
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY,
});
await doc.loadInfo();
console.log('title', doc.title);
My next.config.js:
const nextConfig = {
reactStrictMode: true,
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback.fs = false
config.resolve.fallback.tls = false
config.resolve.fallback.net = false
config.resolve.fallback.child_process = false
}
return config
},
future: {
webpack5: true,
},
fallback: {
fs: false,
tls: false,
net: false,
child_process: false
},
}
module.exports = nextConfig;
Took inspiration/fix from here
Found this answer due to a similar issue. I later learned for next.js, with some of these api libraries, you must call call this type of code (serverside) in two contexts getStaticProps or getServerSideProps. See this and this for more details.
Try changing the import statement to:
const { GoogleSpreadsheet } = require('google-spreadsheet');
Source: https://www.npmjs.com/package/google-spreadsheet
The reason is that the library you require uses some nodejs native modules, like path, fs or child_process.
As part of the build process nextjs will create js bundles for your client and server separately. The issue is that your client build cannot resolve those nodejs modules. As a workaround you can tell nextjs to ignore these modules for the client build only.
next.config.js
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = {
fs: false,
path: false,
}
}
return config
}
}
module.exports = nextConfig;
the library does not support ES6 feature yet
if you look to the module export you will find somthing like this :
module.exports = {
GoogleSpreadsheet,
GoogleSpreadsheetWorksheet,
GoogleSpreadsheetRow,
GoogleSpreadsheetFormulaError,
};
https://github.com/theoephraim/node-google-spreadsheet/blob/master/index.js
change the import statement to commonjs modules like this :
const { GoogleSpreadsheet } = require('google-spreadsheet');

IPFS is not a constructor: Nodejs - IPFS/OrbitDB chatroom

I'm trying to build a Dapp with Nodejs and IPFS/OrbitDB every time, I try to start my App I get the error:
this.node = new IPFS({
^
TypeError: IPFS is not a constructor
This is my basic code without a specific Swarm:
const Ipfs = require('ipfs');
const OrbitDB = require('orbit-db');
class chatroom {
constructor(IPFS, OrbitDB) {
this.OrbitDB = OrbitDB;
this.node = new IPFS({
preload: {enable: false},
repo: "./ipfs",
EXPERIMENTAL: {pubsub: true},
config: {
Bootstrap: [],
Addresses: {Swarm: []}
}
});
this.node.on("error", (e) => {throw (e)});
this.node.on("ready", this._init.bind(this));
}
async _init(){
this.orbitdb = await this.OrbitDB.createInstance(this.node);
this.onready();
}
}
module.exports = exports = new chatroom(Ipfs, OrbitDB);
I'm running on the following version of IPFS: ipfs#0.42.0
I tried it also on an empty Nodejs App and there I had the same error also when I added a specific Swarm to connect to.
I would really appreciate your help, thx for your time in advance.
Kind regards
beni
I did it now like that:
const IPFS = require('ipfs');
async function createNode() {
let node = await IPFS.create(
{
repo: (() => `repo-${Math.random()}`)(),
"Addresses": {
"Swarm": [
"/ip4/0.0.0.0/tcp/4001"
],
"API": "/ip4/127.0.0.1/tcp/5001",
"Gateway": "/ip4/127.0.0.1/tcp/8080"
}
}
);
try {
await node.start();
console.log('Node started!');
} catch (error) {
console.error('Node failed to start!', error);
}
}
(thx #Eugene)

Categories