dataSource flag in typeorm cli - javascript

I'm starting a project with typeorm. My configuration file looks like this:
ormconfig.js
import dotenv from 'dotenv'
dotenv.config();
const {
DATABASE_HOST,
DATABASE_PORT,
DATABASE_NAME,
DATABASE_PASSWORD
} = process.env
export default {
type: 'postgres',
host: DATABASE_HOST,
port: DATABASE_PORT,
database: DATABASE_NAME,
password: DATABASE_PASSWORD,
entities: [
"./api/modules/documents/entity/*.js",
],
migrations: [
"./api/database/migrations/*.js",
],
cli: {
migrationsDir: "./api/database/migrations",
entitiesDir: "api/database/modules/**/entity"
}
}
package.json scripts
"scripts": {
"gulp": "node_modules/gulp-cli/bin/gulp.js",
"start": "nodemon ./src/app.js",
"start:api": "nodemon ./api/server.js",
"typeorm": "node ./node_modules/typeorm/cli.js --config ./ormconfig.js"
},
When i try to run the command yarn typeorm migration:run its show this message:
Runs all pending migrations.
Opções:
-h, --help Exibe ajuda [booleano]
-d, --dataSource Path to the file where your DataSource instance is defined.
[obrigatório]
-t, --transaction Indicates if transaction should be used or not for
migration run. Enabled by default. [padrão: "default"]
-v, --version Exibe a versão [booleano]
Missing required argument: dataSource
What would be datasource flag?
I tried with typeorm cli installed globally, same problem happens

Looks like you are using typeorm 0.3.x in your project while you are following 0.2.x configurations. Check your installed version on your package.json.
If you are using 0.3.x and want to keep with the current version you should follow the documentation: https://typeorm.io/data-source
Otherwise you can just downgrade your version executing:
npm install typeorm#0.2.45

Related

Error: knex: Required configuration option 'client' is missing

I'm new to Node.js, please help me.
What is wrong?
Using typescript, SQLite3 and Knex, with migration.
I get the error when running "yarn knex: migrate" or "knex migrate: latest":
$ knex migrate:latest
Requiring external module ts-node/register
Error: knex: Required configuration option 'client' is missing
These are my files:
package.json:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "ts-node-dev --transpile-only --ignore-watch node-modules --respawn
src/server.ts",
"knex:migrate": "knex --knexfile knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile knexfile.ts migrate:rollback"
},
"devDependencies": {
"#types/express": "^4.17.11",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"espress": "^0.0.0",
"express": "^4.17.1",
"knex": "^0.95.4",
"sqlite3": "^5.0.2"
}
}
knexfile.ts:
import path from'path';
module.exports = {
cliente: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'src', 'database', 'resp.sqlite')
},
migrations: {
directory: path.resolve(__dirname, 'src', 'database', 'migrations'),
},
useNullAsDefault: true,
};
Migration 00_create_organizacoes.ts:
import knex from 'knex';
export async function up(knex: knex) {
return knex.schema.createTable('organizacoes', table => {
table.increments('id').primary();
table.string('razaosocial_org').notNullable();
table.integer('atividade_org').notNullable();
table.timestamp('criacao_org').defaultTo(knex.fn.now());
table.timestamp('atualizacao_org').defaultTo(knex.fn.now());
});
}
export async function down(knex: knex) {
return knex.schema.droptable('organizacoes');
};
My file structure:
enter image description here
Unsuccessful in other treatments.
Looks like you have a typo in your knexfile.ts
The name of the missing property is client and not cliente
The Requiring external module ts-node/register message you get is not the issue, the issue is that in the knexfile.ts the client property is not read. From the example above change the cliente property to client and it is fixed.
What if you have no spelling error, client exist in your configuration, and you are getting this message? Are you using a env file? If yes, In your knexfile.ts print the value from your env file. If it returns undefined, it means that no value was read for the env file. Check if you have the dotenv package installed and configured properly. Also check that your env file has a key called client and the value is available and in the knexfile.ts ensure you are calling the right key from your env.
Finally if the problem is not solved and every other thing is in-place, require dotenv in your package.json file before running a command as shown below.
"migrate:latest": "ts-node -r dotenv/config ./node_modules/knex/bin/cli.js migrate:latest
The ts-node -r dotenv/config ensures that the details in the env file are added to the environment.
The ./node_modules/knex/bin/cli.js starts the knex cli so that the remaining part which is a knex command can be executed.

How to set up configuration of Type ORM with .env file in Nest.JS

I want to set up configuration of TypeORM with .env file, but i have problem when I am trying to run migration script.
What i did:
1.Added scripts to package.json
"migration:generate": "node_modules/.bin/typeorm migration:generate -n",
"migration:run": "node_modules/.bin/typeorm migration:run",
"migration:revert": "node_modules/.bin/typeorm migration:revert",
2.Imported TypeOrmModule in app.module*
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('HOST'),
port: +configService.get<number>('PORT'),
username: configService.get('DATABASE_USERNAME'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
})
}
)],
3. Creaded .env file in root folder
HOST=localhost
PORT=5432
DATABASE_USER=dbuser
DATABASE_PASSWORD=dbpassword
DATABASE=dbname
now I am trying to run migration script like this:
npm run migration:generate -n AddUserTable
and I reciving error like this:
Error during migration generation:
Error: No connection options were found in any orm configuration files.
According to documentation it shuld be some ormconfig.json but it should also working with .env. Please tell me, what is wrong in my case?
Regarding the error message, you should add ormconfig.json in the root project. The .env file does not relate in this case.
Check import ConfigModule.forRoot(). It should be imported first
You can not use forRootAsync for TypeOrmModule if you use these variables in the env file
TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_PORT = 5432
TYPEORM_USERNAME = postgres
TYPEORM_PASSWORD = 12345
TYPEORM_DATABASE = postgres
TYPEORM_SYNCHRONIZE = false
TYPEORM_MIGRATIONS_RUN = false
TYPEORM_ENTITIES = src/modules/**/*.entity.ts
TYPEORM_MIGRATIONS = db/migrations/*.ts
TYPEORM_LOGGING = true
https://github.com/typeorm/typeorm/blob/master/docs/using-ormconfig.md#using-environment-variables
You can also try such scripts:
"migration:run": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:run",
"migration:revert": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:revert",
"migration:create": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:create",
"migration:generate": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:generate"
I was having the same problem. I solved it by following the config instructions in this article, which shows you how to generate a dynamic ormconfig.json file:
https://medium.com/#gausmann.simon/nestjs-typeorm-and-postgresql-full-example-development-and-project-setup-working-with-database-c1a2b1b11b8f
The extra setup is a bit annoying, but it works.
Just a note if you are using typescript - the article is from 2019 and per 2020 updates to nestjs, you'll want to change the src paths to allow for src or dist in the config.service.ts file, eg. change to something like this (depending on your file structure):
entities: ['**/*.entity{.ts,.js}'],
migrationsTableName: 'migration',
migrations: ['src/migration/*.ts'],
cli: {
migrationsDir: 'src/migration',
},
to
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
migrationsTableName: 'migration',
migrations: [__dirname + '/../migration/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migration',
},

Integrating Stylelint with Vue.js

I'm working on trying to integrate stylelint into my freshly created Vue project.
I thought this would be a simple case of using the Stylelint Webpack Plugin but when I run yarn serve, any errors completely freeze it with no output. If I run yarn build, the build will fail as intended but will only print "There was a stylelint error".
My vue.config.js is as follows:
const stylelintPlugin = require('stylelint-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new stylelintPlugin({ files: ['**/*.(vue|scss)'] }),
],
},
};
Here are my current versions from package.json:
"#vue/cli-service": "^3.9.0",
"stylelint": "^10.1.0",
"stylelint-config-recommended": "^2.2.0",
"stylelint-scss": "^3.9.2",
While this may come too late, here are working configurations by using stylelint-config-recommended-scss.
It is an extension to the 3rd party stylelint-scss plugin which needs to be installed along with stylelint itself. Also stylelint-webpack-plugin needs to be installed, which seems to have been missing from your setup.
Install dev dependencies:
# First remove an unnecessary one you had (with NPM):
npm uninstall stylelint-config-recommended
# Or with Yarn:
yarn remove stylelint-config-recommended
# Install dev deps with NPM:
npm i -D stylelint stylelint-scss stylelint-config-recommended-scss stylelint-webpack-plugin
# Or with Yarn:
yarn add -D stylelint stylelint-scss stylelint-config-recommended-scss stylelint-webpack-plugin
In your vue.config.js configuration file:
const StyleLintPlugin = require('stylelint-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new StyleLintPlugin({
files: ['src/**/*.{vue,scss}'],
}),
],
},
};
Create a file stylelint.config.js in your project's root folder:
module.exports = {
extends: 'stylelint-config-recommended-scss',
rules: {
'selector-pseudo-element-no-unknown': [
true,
{
ignorePseudoElements: ['v-deep']
}
]
}
};
In package.json you can add this lint:scss command (run by npm run lint:scss). It tries to run autofix on all rules, but please note that not all rules can be autofixed.
In that case the script will output a list of error lines and exit on error. You need to go and fix these by hand, and then re-run the script to see that the errors got fixed:
{
"scripts": {
"lint:scss": "stylelint ./src/**/*.{vue,scss} --fix"
}
}
Hope this helps! Please add a comment if I missed something.
my configuration is the same like ux.engineer written
but when i try run scripts npm run lint:scss then I have
node_modules/stylelint/node_modules/get-stdin/index.js:13
for await (const chunk of stdin) {
^^^^^
SyntaxError: Unexpected reserved word
it turned out that I had the wrong (old) node version, so pay attention for that

Node.js: OAuth2Strategy requires a clientID option

I am setuping the MERN stack project, which was created by another developer and I am getting the error:
node_modules/passport-oauth2/lib/strategy.js:82
[0] if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
[0] ^
[0]
[0] TypeError: OAuth2Strategy requires a clientID option
If I understand correctly, there should be clientID in .env file and there's no such file in the project, right?
For me, I did something like this
passport.use(
new FacebookStrategy(
{
clientID: config.FACEBOOK_APP_ID,
clientSecret: config.FACEBOOK_CONSUMER_SECRET,
callbackURL: config.FACEBOOK_REDIRECT_URL,
profileFields: ['id', 'displayName', 'email']
},
But I forgot to add my FACEBOOK_APP_ID in my config file. Just make sure that your clientId being passed is not null or undefined
Be sure to npm install dotenv, and add require('dotenv').config(); to the top of your app.js file.
While the answer from #ColsonRice wasn't exactly the reason I received the above error OAuth2Strategy requires a clientID option, it did point me in the right direction. In trying to get my Typescript version of my NodeJs express server working on Heroku I had changed (10 commits back), my package.json start script from
"start": "node -r dotenv/config ./dist/index.js",
to
"start": "node dist/index.js",
Change the development start up to use an alternative start command with the dotenv/config option back in resolved my issue. The last 4 lines of my scripts section of package.json are as follows:
"dev": "nodemon --exec npm run restart",
"restart": "rimraf dist && npm run build && npm run devstart",
"devstart": "node -r dotenv/config ./dist/index.js",
"start": "node dist/index.js",
So for me, the negative score for Colson is unjustified as it indirectly helped me resolve my issue.
Be sure to npm install dotenv, and add require('dotenv').config(); to the top of your app.js file.
The Problem is config.FACEBOOK_CLIENT_ID instead of config.FACEBOOK_APP_ID
Error Strategy:
passport.use(
new FacebookStrategy(
{
clientID: config.FACEBOOK_CLIENT_ID,
clientSecret: config.FACEBOOK_CONSUMER_SECRET,
callbackURL: config.FACEBOOK_REDIRECT_URL,
profileFields: ['id', 'displayName', 'email']
},
Correct Strategy:
passport.use(
new FacebookStrategy(
{
clientID: config.FACEBOOK_APP_ID,
clientSecret: config.FACEBOOK_CONSUMER_SECRET,
callbackURL: config.FACEBOOK_REDIRECT_URL,
profileFields: ['id', 'displayName', 'email']
},

how to execute es6 scripts from CLI

I have the latest NodeJS installed and for any JavaScript files, I can execute it with node myscript.js but recently I'm learning es6 and for some of the latest syntax, it just pop out some errors/exceptions while executing. I tried babel-cli, but didn't seem to work as it is for compile es6 to 5 not for command line execute.
1) To enable the support of ES6, use the --harmony flag:
node --harmony myscript.js
This will enable the available ES6 syntax in node. But notice it's currently a limited subset of the ES6 standard (see the compatibility table).
2) To have a complete compatibility, you have to use babel node.
Install #babel/node to get a babel-node executable which works exactly the same as Node.js's CLI, only it will compile ES6 code before running it.
babel-node myscript.js
For simple ES6 or even Typescript experimentation, maybe Deno could be considered nowadays. It supports newest ES (and TS) out of the box without needing any additional tooling.
#source1
https://dev.to/geekygeeky/get-started-with-es6-javascript-for-writing-nodejs-using-express-544h
#create dir /project1
mkdir /project1
cd /project1
#install babel etc
npm i #babel/cli #babel/core #babel/node #babel/preset-env --save-dev
npm i #babel/plugin-proposal-class-properties #babel/plugin-proposal-object-rest-spread --save-dev
npm i rimraf nodemon --save-dev
#initialize project1
#https://philna.sh/blog/2019/01/10/how-to-start-a-node-js-project/
npm init
#edit /project1/package.json
nano /project1/package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rimraf dist && babel src --out-dir dist --copy-files",
"start": "node dist/app.js",
"start:dev": "nodemon --exec babel-node src/app.js"
},
#edit /project1/.babelrc
nano /project1/.babelrc
{ "presets": [
["#babel/env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
]
}
#install express
npm i express --save
#open a bash shell
#create /project1/src
mkdir src
cd src
#edit /project1/src/app.js
nano /project1/src/app.js
import express, { json } from 'express';
import items from './items';
const app = express();
app.use(json())
const PORT = process.env.PORT || 3000;
app.get('/', async (req, res) => {
res.json({ status: true, message: "Our node.js app works" })
});
app.get('/items', (req, res) => {
res.json({ status: true, message: "Fetched all items", data: items })
})
app.listen(PORT, () => console.log(`App listening at port ${PORT}`));
#edit /project1/src/items.js
nano items.js
const items = [
{
id: 1,
username: "John doe",
cartItems: ['football', 'ps5', 'cd-rom'],
},
{
id: 2,
username: "Jane doe",
cartItems: ['mobile phone', 'game pad'],
}
];
export default items;
#open another bash shell
#run server
cd /project1
npm run start:dev
#keep the server running
#check your app via browser
http://localhost:3000
http://localhost:3000/items

Categories