I have a basic nestjs app, I'm trying to use winston as logger service... this breaks my app and I really don't know to fix/revert this.
I've tried uninstalling the winston packages, rm node_modules and npm install again, nothing is working.
node -v: v11.15.
nest -v: 7.1.5
yarn -v: 1.22.4
npm -v: 6.14.5
The error I get:
[11:37:19 AM] Found 0 errors. Watching for file changes.
internal/modules/cjs/loader.js:670
throw err;
^
Error: Cannot find module './app.module'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:668:15)
at Function.Module._load (internal/modules/cjs/loader.js:591:27)
at Module.require (internal/modules/cjs/loader.js:723:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/dtmirror/app-api/dist/src/main.js:4:22)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
package installed:
npm i winston
LoggerService:
import * as winston from 'winston';
import { LoggerOptions } from 'winston';
export class LoggerService {
private logger;
public static loggerOptions: LoggerOptions = {
transports: [
new winston.transports.File({ filename: 'app.log' })
]
}
constructor(private context: string, transport?) {
this.logger = (winston as any).createLogger(LoggerService.loggerOptions);
}
log(message: string): void {
const currentDate = new Date();
this.logger.info(message, {
timestamp: currentDate.toISOString(),
context: this.context,
})
}
}
main.ts:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { LoggerService } from '../logger.service'; // <-- this breaks everything
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
The moment I run yarn start:dev in this stage everything breaks...
Seems like a bad import for the AppModule. According to comments, logger was outside the src directory, which ends up causing the dist to take on a different shape
Related
I'm trying to write a test case in a NextJS application using Jest. On running the test, below error occurs:
/Users/abhajan/Work/Tusk/tusk-app/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
10 | import { useAccount, useBalance, useNetwork, useProvider } from "wagmi";
11 | import Web3 from "web3";
> 12 |
| ^
13 | export default function BlockchainInfo() {
14 | // TODO: Check if user is authenticated first
15 | return (
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1422:14)
at Object.<anonymous> (node_modules/rpc-websockets/dist/lib/server.js:40:13)
at Object.<anonymous> (node_modules/rpc-websockets/dist/index.js:30:38)
at Object.<anonymous> (node_modules/#solana/web3.js/lib/index.cjs.js:15:21)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/SolAddress/SolAddress.ts:2:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/SolAddress/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/methods/requestMessage.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/MoralisAuth.ts:2:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/index.ts:1:1)
at Object.<anonymous> (node_modules/moralis/src/index.ts:3:1)
at Object.<anonymous> (components/blockchain-info/index.tsx:12:55)
at Object.<anonymous> (pages/index.tsx:10:62)
at Object.<anonymous> (__tests__/index.test.tsx:7:53)
Below is the setup for jest config in jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
transformIgnorePatterns: ['node_modules/(?!uuid)/'],
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Below is the test file index.test.tsx:
import { render } from '#testing-library/react';
import Home from 'pages/index';
import '#testing-library/jest-dom';
describe('Home', () => {
it('renders homepage unchanged', () => {
const { container } = render(<Home />);
expect(container).toMatchSnapshot();
});
});
On running the test file, the below error occurs:
Details:
/Users/abhajan/Work/Tusk/tusk-app/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
Not sure if the regex pattern in transformIgnorePatterns is correct or not. Any kind of help is appreciated :)
I can't access this module I'm exporting. I have no clue what's wrong.
I'm trying to export a database connection so it's available everywhere.
database.js
import { Sequelize } from 'sequelize';
var server = 'aggregatesqlserver.database.windows.net'
var database = 'AGGREGATEDEVDB'
var username = '****'
var password = '****'
var driver= '{ODBC Driver 17 for SQL Server}'
const sequelize = new Sequelize(database, username, password, {
host: server,
dialect: "mssql"
});
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
module.exports = sequelize;
When I try to access if from this script
main.ts
import { NestFactory } from '#nestjs/core';
import { NestExpressApplication } from '#nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
import { createConnection, Connection} from "typeorm";
const db = require('./config/database');
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('hbs');
const [results, metadata] = await db.query("UPDATE [dbo].[storedProc] SET someData = RAND() WHERE columnID = 1");
await app.listen(3000);
}
bootstrap();
It gives me this error no matter what...
Error: Cannot find module './config/database'
Require stack:
- /Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/dist/main.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15)
at Function.Module._load (internal/modules/cjs/loader.js:730:27)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/src/main.ts:7:12)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Here's the file system
Any clue on the problem...?
This behavior happens because you try to import a Javascript file from Typescript file. You can try:
1.
import * as db from './config/database';
Add this characteristic to allow JS modules import in tsconfig.json or your tsconfig
{
"compilerOptions": {
"allowJs": true
}
}
Sometimes such conflicts happen due to using ES5 module syntax instead of ES6 module syntax.
To avoid such problem try using only one module syntax, either the es5 or the es6
Try using
import db from './config/database';
instead of
const db = require('./config/database');
I'm trying to test GraphQL server with Jest and Knex. I had a hard time figuring out how to use knexfile in typescript. But now everything is working fine for development and production envs, except for testing.
Here's my current knexfile.ts:
// knexfile.ts
const defaults = {
client: 'pg',
connection: {
host: DB_HOST,
user: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE
},
pool: {
min: 2,
max: 10
},
migrations: {
extension: 'ts',
directory: './migration',
tableName: 'knex_migrations'
},
seeds: {
extension: 'ts',
directory: './seed'
}
};
interface KnexConfig {
[key: string]: object;
}
const knexConfig: KnexConfig = {
local: {
client: 'sqlite3',
connection: {
filename: './dev.sqlite3'
}
},
development: {
...defaults,
debug: true,
useNullAsDefault: true
},
production: {
...defaults
}
};
/**
* `export default` does not work, causes `client` missing problem
* at database migration.
*/
export = knexConfig;
This is global setup for Jest:
// globalSetup.ts
export = async () => {
try {
// Start http server
await httpServer.listen(PORT);
// Rollback and migrate
// await knex.migrate.rollback().then(() => knex.migrate.latest());
knex.migrate.latest();
} catch (err) {
// Log the error
logger.error('', err);
}
};
This is global teardown:
// globalTeardown.ts
export = async () => {
try {
await knex.migrate.rollback();
// Shutdown server
httpServer.close(() => logger.info('Server closed'));
} catch (err) {
// Log the error
logger.error('', err);
}
};
It keeps giving me error:
Unhandled rejection SyntaxError: Unexpected token *
/home/my/knex-graphql/migration/20190821235716_create_user.ts:1
import * as Knex from 'knex';
^
SyntaxError: Unexpected token *
at Module._compile (internal/modules/cjs/loader.js:872:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Function.<anonymous> (/home/my/knex-graphql/node_modules/#sentry/node/src/integrations/console.ts:37:43)
at Function._load (/home/my/knex-graphql/node_modules/#sentry/node/src/integrations/http.ts:73:43)
at Module.require (internal/modules/cjs/loader.js:830:19)
at require (internal/modules/cjs/helpers.js:68:18)
at FsMigrations.getMigration (/home/my/knex-graphql/node_modules/knex/lib/migrate/sources/fs-migrations.js:84:12)
at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:82:69
at arrayFilter (/home/my/knex-graphql/node_modules/lodash/lodash.js:582:11)
at filter (/home/my/knex-graphql/node_modules/lodash/lodash.js:9173:14)
at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:81:13
at tryCatcher (/home/my/knex-graphql/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:517:31)
at Promise._settlePromise (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:574:18)
From previous event:
at Migrator.latest (/home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:71:8)
at /home/my/knex-graphql/test/global/setup.ts:24:32
at Generator.next (<anonymous>)
at fulfilled (/home/my/knex-graphql/test/global/setup.ts:5:58)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
Tech stack: Apollo-server-express, TypeScript, Knex.js, PostgreSQL, Jest
You need to add ts-jest, which will transpile your ts files for jest.
Install it
npm install --save-dev ts-jest
Add default ts-jest config
npx ts-jest config:init
we use something a bit like this in our knexfile.js
require('ts-node/register');
require('dotenv').config();
const {
SERVER_HOST,
SERVER_USER,
SERVER_PASSWORD,
SERVER_DATABASE,
SERVER_DATABASE_TEST,
} = process.env;
I had a perfectly working relay modern app with 1.1.0 babel-plugin-relay + react-relay + react-compiler + graphql 0.10.x, react 15.5.x but since upgrading all of them to 1.4.1 and graphql to 0.11.7 and react to 16.0.0 I keep getting this error when running npm start:
ERROR in ./src/main.js
Module build failed: Error: BabelPluginRelay: Expected plugin context to include "types", but got:[object Object]
at BabelPluginRelay (/Users/johndoe/testing/atc/node_modules/babel-plugin-relay/lib/BabelPluginRelay.js:36:11)
at Object.<anonymous> (/Users/johndoe/testing/atc/src/babelRelayPlugin.js:28:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /Users/johndoe/testing/atc/node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/main.js
webpack: Failed to compile.
with babel-plugin-relay like so:
babelRelayPlugin.js:
const babelRelayPlugin = require('babel-plugin-relay')
const { introspectionQuery, buildClientSchema, printSchema } = require('graphql/utilities')
const request = require('sync-request')
const fs = require('fs')
const path = require('path')
const schemaPath = path.join(__dirname, 'schema');
const graphqlHubUrl = 'https://myhub.com/dev/graphql'
const response = request('POST', graphqlHubUrl, {
qs: {
query: introspectionQuery
}
})
console.log('response ', response)
const schema = JSON.parse(response.body.toString('utf-8'))
console.log('schema ', schema)
const graphQLSchema = buildClientSchema(schema.data);
fs.writeFileSync(
`${schemaPath}.graphql`,
printSchema(graphQLSchema)
);
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
and webpack.config.js:
query: {
presets: ['env', 'react', 'stage-2'],
plugins: ['relay', 'transform-class-properties', __dirname + '/src/babelRelayPlugin']
}
the question is why ? and how I can fix it? because in the response I can clearly see types:
Solved it.
Had to change this:
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
to this:
module.exports = babelRelayPlugin(schema.data.__schema, {
abortOnError: true
})
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.
Tutorial: https://www.sitepoint.com/node-js-mvc-application/
Git for my project: https://github.com/christoph88/node-js-mvc-tut/
I have an error when I try to launch the server:
~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.
'use strict';
const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');
const server = new Hapi.Server();
server.connection({ port: Settings.port });
server.register([
require('vision'),
require('inert')
], (err) => {
Hoek.assert(!err, err);
server.views({
engines: { pug: require('pug') },
path: Path.join(__dirname, 'lib/views'),
compileOptions: {
pretty: false
},
isCached: Settings.env === 'production'
});
// Add routes
server.route(Routes);
});
Models.sequelize.sync().then(() => {
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
});
Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.
I have got it working by moving my index.js file to the models folder.
This file has the necessairy scripts that dispatches sequelise in the model thus fixing the problem.
Make sure you have exported the db in index.js
module.exports = db
and declared a db variable at the beginning of the file
var db = {}