Include extra files inside app.asar using electron - javascript

It's a Vue app with electron-builder
{
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps",
},
"main": "background.js",
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2",
"vue-router": "^3.3.2",
"vuetify": "^2.2.33"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.4.0",
"#vue/cli-plugin-eslint": "~4.4.0",
"#vue/cli-plugin-router": "~4.4.0",
"#vue/cli-plugin-typescript": "~4.4.0",
"#vue/cli-service": "~4.4.0",
"electron": "^6.1.12",
"typescript": "^3.9.5",
"vue-cli-plugin-electron-builder": "~1.4.6",
"vue-cli-plugin-vuetify": "~2.0.5",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.3.0"
}
}
When I use npm run electron:build, this structure is generated:
And this is the content of app.asar:
background.js include all the dependencies. There are some external modules (from node_modules) that read files using something like fs.readFile(__dirpath + '/file'). As expected, these files are not included in the generated bundle, so I need to add them.
I've tried to use this in vue.config.js:
module.exports = {
lintOnSave: true,
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
builderOptions: {
extraFiles: [
'node_modules/module/file'
]
}
}
}
}
But the file is included outside the app.asar, even with extraResources, and thus fs.readFile(__dirpath + '/file') did not find the file.
How can I include files inside app.asar?

The only way I found was using the public directory. Any file inside public/ will be copied to app.asar.
However, the file I need to copy belongs to an external lib, so to not make this file part of my project, I gitignored it and copy just before the build, using npm scripts.
"scripts": {
"build": "cp node_modules/lib/file public && vue-cli-service electron:build -wl",
"serve": "mkdir -p dist_electron && cp node_modules/lib/file dist_electron && vue-cli-service electron:serve"
}

I found out the path for files have to be relative path from dist_electron/bundled(or maybe other directory). So if we have directory named keys in root, the config should to be something like bellow.
module.exports = {
pluginOptions: {
electronBuilder: {
nodeIntegration: true,
builderOptions: {
files: [
"**/*",
{
from: "../../keys",
to: "./keys",
filter: ["**/*"],
},
],
},
},
},
};

Related

CSS.supports is not defined in Jest test

I tried a lot to search for a solution to my problem all over the internet, however I couldn't find anything that could help me.
I have a JS utility file that allows me to test values.
Here is one of the functions that compose it :
const colorIsValid = (color) => {
if (!color || typeof color !== 'string') {
return false
}
if (CSS !== undefined) {
if (CSS.supports('color', color)) {
return true
}
throw new Error(`The provided color : "${color}" is not valid`)
}
throw new Error('Your navigator do not support CSS Api')
}
export { colorIsValid }
Everything works fine when I do a manual test on different browsers.
However when I run my tests with Jest I get the following error:
ReferenceError: CSS is not defined
here is my current environment.
// package.json
{
"name": "vue-polygon-grid",
"version": "1.0.0",
"description": "Interactive polygon structure for Vue.js",
"author": {
"name": "Guyomar Alexis",
"email": "contact#ag-dev.fr",
"url": "https://ag-dev.fr/"
},
"main": "dist/data-tables.min.js",
"homepage": "https://github.com/ga-devfront/vue-polygon-grid-private",
"keywords": [
"vue3",
"vuejs",
"vue",
"grid",
"polygon",
"composition"
],
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "jest"
},
"dependencies": {
"core-js": "^3.20.2",
"vue": "^3.0.0"
},
"devDependencies": {
"#babel/core": "^7.16.7",
"#babel/preset-env": "^7.16.8",
"#vue/cli-plugin-babel": "~4.5.15",
"#vue/cli-plugin-eslint": "~4.5.15",
"#vue/cli-service": "~4.5.15",
"#vue/compiler-sfc": "^3.2.26",
"#vue/eslint-config-airbnb": "^6.0.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.4.6F",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^25.3.4",
"eslint-plugin-vue": "^8.2.0",
"jest": "27.4.7",
"jest-junit": "13.0.0",
"jest-transform-stub": "^2.0.0",
"sass": "^1.38.0",
"sass-loader": "^10"
}
}
// jest.config.js
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
"collectCoverageFrom": [
"**/utility/*.{js,jsx}",
],
coverageReporters: ['html', 'text', 'text-summary', 'cobertura'],
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|jpeg|svg|ttf|woff|woff2)$': 'jest-transform-stub',
},
reporters: [
'default',
['jest-junit', { outputDirectory: 'coverage' }],
],
};
Does anyone have a solution so I can test my methods?
Thank you in advance for taking the time to read me.
jest runs via Node runtime, meaning there are no browser APIs. You will need to mock it. Look into jest setupFiles.
Create a setup file:
global.CSS = {
supports: (k, v) => false,
}
Then use that setup file to add CSS object onto global object.
This answer might also be helpful.
If you really must have DOM APIs you can include package JSDOM that can help. In my opinion in most cases it’s unnecessary dependency.
From your question it sounds like you just need your tests to run. Do you really need to set up global CSS object? Are you sure you’re not testing implementation details?

How to add Sapper to existing Svelte project?

I have extensive applications in svelte, later I need to attach a sapper to it for further work, it is possibly? I try do it via:
npm i #sapper
but when I try to import something from this package e.q.:
import { goto } from '#sapper/app';
compiler throw me that i have no dependency to this sapper methods :(
I have no idea how to attach sapper to my project
my rollup
import svelte from "rollup-plugin-svelte";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
// library that helps you import in svelte with
// absolute paths, instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
import alias from "#rollup/plugin-alias";
const production = !process.env.ROLLUP_WATCH;
// configure aliases for absolute imports
const aliases = alias({
resolve: [".svelte", ".js"], //optional, by default this will just look for .js files or folders
entries: [
{ find: "components", replacement: "src/components" },
{ find: "views", replacement: "src/views" },
{ find: "assets", replacement: "src/assets" },
],
});
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write("bundle.css");
},
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"],
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
// for absolut imports
// i.e., instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
aliases,
],
watch: {
clearScreen: false,
},
};
my package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public -s",
"build:tailwind": "tailwind build public/assets/styles/index.css -o public/assets/styles/tailwind.css",
"build:fontawesome": "mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/webfonts && mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/css && cp -a ./node_modules/#fortawesome/fontawesome-free/webfonts public/assets/vendor/#fortawesome/fontawesome-free/ && cp ./node_modules/#fortawesome/fontawesome-free/css/all.min.css public/assets/vendor/#fortawesome/fontawesome-free/css/all.min.css",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && rm -rf public/build && npm install && npm run build:tailwind && npm run build:fontawesome && npm run dev"
},
"devDependencies": {
"#rollup/plugin-commonjs": "^16.0.0",
"#rollup/plugin-node-resolve": "^10.0.0",
"rollup": "^2.3.4",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1"
},
"dependencies": {
"#fortawesome/fontawesome-free": "5.14.0",
"#popperjs/core": "2.5.1",
"#rollup/plugin-alias": "3.1.1",
"#rollup/plugin-replace": "^2.3.4",
"#tailwindcss/custom-forms": "0.2.1",
"body-parser": "^1.19.0",
"chart.js": "2.9.3",
"compression": "^1.7.4",
"express": "^4.17.1",
"express-session": "^1.17.1",
"fontawesome-svelte": "^2.0.1",
"node-fetch": "^2.6.1",
"node-sass": "^5.0.0",
"page": "^1.11.6",
"polka": "^0.5.2",
"rollup-plugin-scss": "^2.6.1",
"session-file-store": "^1.5.0",
"sirv": "^1.0.10",
"sirv-cli": "1.0.6",
"svelte-routing": "1.4.2",
"tailwindcss": "1.8.10"
}
}
I was looking for this answer, I think the #Romain Durand answer is the closest, I don't think we can add ssaper to an existing svelte project. I would have to initialize project in ssaper and use svelte.

Vue CLI - No PostCSS config found

i have a package.json as this:
{
"name": "dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"apexcharts": "^3.8.4",
"axios": "^0.19.0",
"core-js": "^2.6.5",
"lodash": "^4.17.15",
"moment": "^2.24.0",
"vue": "^2.6.10",
"vue-apexcharts": "^1.5.1",
"vue-numerals": "^3.0.5",
"vue-router": "^3.1.3",
"vue-virtual-scroll-list": "^1.4.4",
"vuetify": "2.1.13",
"vuex": "^3.1.2",
"vuex-map-fields": "^1.3.6",
"vuex-persist": "^2.2.0"
},
"devDependencies": {
"#mdi/font": "^3.8.95",
"#vue/cli-plugin-babel": "^3.9.0",
"#vue/cli-plugin-eslint": "^3.9.0",
"#vue/cli-service": "^3.9.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"sass": "^1.17.4",
"sass-loader": "^7.1.0",
"typeface-roboto": "^0.0.75",
"vue-cli-plugin-vuetify": "^2.0.5",
"vue-template-compiler": "^2.6.10",
"vuetify-loader": "^1.2.2"
}
}
As I did the setup for this project via Vue cli I selected that options as Eslint, Babel and so on are incapsulated in the package.json. I put them in several files now: .eslintrc.js, babel.config.js, and postcss.config.js. Can I do this just like that - creating these files and remove the contents from the package.json?
The contents of the postcss.config.js is this:
module.exports = {
plugins: {
autoprefixer: {},
},
};
When I build this I always get this message:
Module build failed (from ./node_modules/postcss-loader/src/index.js):
Error: No PostCSS Config found in: /Users/dev/Sites/dev/src/node_modules/vuetify/src/directives/ripple
at /Users/dev/Sites/dev/src/resources/views/dashboard/node_modules/postcss-load-config/src/index.js:91:15
# /Users/dev/Sites/dev/src/node_modules/vuetify/src/directives/ripple/VRipple.sass 4:14-329 14:3-18:5 15:22-337
Before that I see this message at top:
65% building 852/919 modules 67 active /Users/dev/Sites/dev/src/resources/views/dashboard/node_modules/axios/lib/core/transformData.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
Does this mean that I need to use the sass-loader which is specified in the package.json in the postcss.config.js as well? I am bit puzzled, because on another project I have the same configuration and no other content in the postcss.config.js and I do not get error messages about missing plugins. Thanks!
I advise you to try launching vue ui in the console. After that in the "dependencies" category, you have to try to uninstall packages for CSS-processors and then reinstall it. Probably some of these packages are corrupted.

SyntaxError: Unexpected token 'export' in Nodejs project with Typescript and Webpack

I have tried to find an answer to this solution but the answers I have found are usually to do with adding 'module' to a script tag (which doesnt apply in my case since I'm not writing browser code) or using import/export in a javascript file (which is not currently supported by Node) which means the need to use babel or typescript. Since I am seeing this error in a typescript project, I don't expect to see this error.
Actually, I have 2 typescript/webpack projects (with near identical setup, project A depends on project B) 1 importing definitions from the other.
In project B, I have several classes, 2 of which are exported, plus some other definitions. In project B's index.ts:
export * from './types';
export * from './specService/spec-option-service.class';
export * from './converter/xpath-converter.class';
and those are exported like so:
// types.ts
//
export interface IElementInfo {
readonly id?: string;
readonly recurse?: string;
readonly discards?: ReadonlyArray<string>;
readonly descendants?: {
readonly by?: string;
readonly throwIfCollision?: boolean;
readonly throwIfMissing?: boolean;
};
}
// ... plus other similarly defined exports
// specService/spec-option-service.class.ts
//
export class SpecOptionService { ...
// converter/xpath-converter.class.ts
//
export class XpathConverter { ...
And then in project B's index.ts, I export all the definitions (export * from blah) for use by the client as shown at the top of this post.
When I build project B, there is no such issues with the export.
After installing project B into project A
from a typescript file I am importing using:
import * as ProjectB from 'projectb';
Webpack successfully even builds project A's bundle, with no error. The error occurs at runtime, in this case when I go to run the tests at which point I see the following:
/Users/User/dev/github/js/projecta/node_modules/projectb/lib/index.ts:2
export * from './types';
^^^^^^
SyntaxError: Unexpected token 'export'
at Module._compile (internal/modules/cjs/loader.js:892:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.projectb (/Users/User/dev/github/js/projecta/dist/projecta-test-bundle.js:292:18)
At the end of projectb's webpack bundle, I found the following:
module.exports = webpack_require(/*! ./lib */"./lib/index.ts");
which I believe is at fault. Why does the bundle built by webpack for an "es5" target contain references to typescript? Isn't this bound to fail? I would have expected a require on the generated index.js file (not index.ts).
This is the first time I've done import/export across project boundaries in typescript so I know that I doing something wrong but what?
The tsconfig.json file in both projects are the same:
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "Node",
"noImplicitAny": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es5",
"types": [
"mocha", "node"
],
"lib": [
"es5",
"es2015",
"es6",
"dom"
]
},
"include": [
"lib/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
And the webpack config:
{
devtool: 'source-map',
entry: {
index: './lib/index.ts'
},
target: 'node',
mode: mode,
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.ts(x?)$/,
use: 'ts-loader'
},
{
test: /\.json$/,
use: 'json-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }),
new webpack.BannerPlugin({
banner: '#!/usr/bin/env node',
raw: true
})
],
resolve: {
extensions: ['.ts', '.js', '.json']
},
watchOptions: {
ignored: /node_modules/
},
output: {
filename: 'projecta-bundle.js',
sourceMapFilename: 'projecta-bundle.js.map',
path: path.join(__dirname, 'dist'),
libraryTarget: 'commonjs'
}
}
Project A and B are plastikfan/jaxom and plastikfan/zenobia respectively. Before publishing the latest version of jaxom to npm, I am performing pre-npm-publish check (learnt that this is a wise thing to do with early npm packages) to check that clients can use the package as expected. (I've had problems in tha past where I've made a mistake in exporting something, but this does not become apparent until a client tries to use it. It's not somthing you can check for as far as I know before you publish. The advised way to to do this is to pack up your package using nom pack then install it into the client).
fyi, zenobia package.json is (cutdown version):
{
"name": "zenobia",
"version": "0.0.1",
"main": "lib/index.ts",
"scripts": {
"t": "mocha ./dist/zenobia-test-bundle.js",
"test": "npm audit --skip-unused && npm run t",
"build": "npm run build:d",
"build:d": "webpack -d --env.mode development",
"build:p": "webpack -p --env.mode production",
"build:t": "webpack --config webpack.config.test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/plastikfan/zenobia.git"
},
"dependencies": {
"#types/node": "^12.12.14",
"#types/ramda": "^0.26.36",
"jaxine": "^2.0.1",
"jaxom": "file:../NPM-LOCAL/jaxom-0.0.1.tgz",
"ramda": "^0.26.1",
"xmldom": "^0.1.27",
"xpath": "0.0.27"
},
"devDependencies": {
"#commitlint/cli": "^8.3.3",
"#commitlint/config-conventional": "^8.2.0",
"#types/chai": "^4.2.5",
"#types/dirty-chai": "^2.0.2",
"#types/mocha": "^5.2.7",
"#types/sinon": "^7.5.1",
"#types/sinon-chai": "^3.2.3",
"chai": "^4.2.0",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.0.2",
"depcheck": "^0.9.1",
"dirty-chai": "^2.0.1",
"mocha": "^6.2.2",
"nyc": "^14.1.1",
"precommit-hook": "^3.0.0",
"raw-loader": "^4.0.0",
"rimraf": "^3.0.0",
"semistandard": "^14.2.0",
"shebang-loader": "0.0.1",
"sinon": "^7.5.0",
"snazzy": "^8.0.0",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"tslint-config-semistandard": "^8.0.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-config-utils": "^2.3.1",
"webpack-node-externals": "^1.7.2"
}
}
And jaxom's cutdown package.json:
{
"name": "jaxom",
"main": "./lib/index.ts",
"scripts": {
"clean": "rimraf dist && rimraf decl",
"t": "mocha ./dist/jaxom-test-bundle.js",
"test": "npm audit --skip-unused && npm run t",
"build": "npm run build:d",
"build:d": "webpack -d --env.mode development",
"build:p": "webpack -p --env.mode production",
"build:t": "webpack --config webpack.config.test.js"
},
"dependencies": {
"#types/ramda": "^0.26.36",
"#types/xregexp": "^3.0.30",
"jinxed": "0.0.2",
"moment": "^2.24.0",
"ramda": "^0.26.1",
"xmldom-ts": "^0.3.1",
"xpath-ts": "^1.3.13",
"xregexp": "^4.2.4"
},
"devDependencies": {
"#commitlint/cli": "^8.2.0",
"#commitlint/config-conventional": "^8.2.0",
"#types/chai": "^4.2.5",
"#types/dirty-chai": "^2.0.2",
"#types/mocha": "^5.2.7",
"#types/sinon": "^7.5.1",
"#types/sinon-chai": "^3.2.3",
"chai": "^4.2.0",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.0.2",
"depcheck": "^0.9.1",
"dirty-chai": "^2.0.1",
"json-loader": "^0.5.7",
"mocha": "^6.2.2",
"precommit-hook": "^3.0.0",
"raw-loader": "^4.0.0",
"rimraf": "^3.0.0",
"sinon": "^7.5.0",
"sinon-chai": "^3.3.0",
"snazzy": "^8.0.0",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"tslint-config-semistandard": "^8.0.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-config-utils": "^2.3.1",
"webpack-node-externals": "^1.7.2"
}
}
For me, it was the module key in tsconfig.json.
I changed it from this:
"module": "esnext"
to this:
"module": "commonjs"
I think tsconfig can be a problem here.
Because when you are importing import * as ProjectB from 'projectb'; your projectB files will not be transpiled by typescript because of include and exclude properties of projectA tsconfig. Try add projectB to the compilation process of projectA.
Something like include: [ "lib/**/*", "my/path/to/projectB/**"] in projectA tsconfig.
Make sure you're running .js file not .ts.
Try adding "type":"module" to the package.json.

No metadata found for class-validator

I am trying to use a ValidationPipe but no matter how I write my code I get the following warning when sending a request: No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
My route looks something like this:
#Get()
#UsePipes(new ValidationPipe({ transform: true }))
async findAll(#Query() queryDto: QueryDto) {
return await this.myService.findAll(queryDto);
}
And my DTO looks something like this:
export class queryDto
{
#ApiModelProperty({
description: 'Maximum number of results',
type: Number,
example: 50,
default: 50,
required: false
})
readonly limit: number = 50;
}
I tried using the ValidationPipe several ways, following the doc, but nothing works for me. I know it does not work because although the request gets a response, the default value that I wrote in my DTO for the property limit, which is 50, is not used when the query is empty. Therefore, when no limit is provided in the query, limit's value is undefined, whereas it should be 50 (which means the ValidationPipe is not used).
My package.json seems correct:
npm ls class-validator
api-sport#0.0.1 /home/pierre_t/Bureau/dev/ApiSport
└── class-validator#0.9.1
Full package.json:
{
"name": "api-sport",
"version": "0.0.1",
"description": "",
"author": "",
"license": "MIT",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "nodemon",
"start:debug": "nodemon --config nodemon-debug.json",
"start:prod": "pm2 start ./src/main.js --no-daemon",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^6.0.5",
"#nestjs/core": "^6.0.5",
"#nestjs/platform-express": "^6.0.5",
"#nestjs/swagger": "^3.0.1",
"#nestjs/typeorm": "^6.0.0",
"#types/lodash": "^4.14.123",
"class-transformer": "^0.2.0",
"class-validator": "^0.9.1",
"dotenv": "^7.0.0",
"hbs": "^4.0.3",
"mysql": "^2.16.0",
"pm2": "^3.4.1",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.3.3",
"swagger-ui-express": "^4.0.2",
"typeorm": "^0.2.16"
},
"devDependencies": {
"#nestjs/testing": "^6.0.5",
"#types/express": "^4.16.0",
"#types/jest": "^23.3.13",
"#types/node": "^10.14.4",
"#types/supertest": "^2.0.7",
"jest": "^23.6.0",
"nodemon": "^1.18.9",
"prettier": "^1.15.3",
"supertest": "^3.4.1",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"tsconfig-paths": "^3.7.0",
"tslint": "5.12.1",
"typescript": "^3.4.1"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Why do I get this message and how can I use ValidationPipe?
This is because you are using class-validator but without any validations, see this issue:
Basically, it warns that you don't have any metadatas in the storage,
which means you haven't used any decorator from class-validator. That
means you don't perform any validation, so you should just pass
validate: false option to buildSchema to disable automatic validation.
I'm not sure if you can turn of validation for nest's ValidationPipe, but alternatively you can just add an assertion to your dto (if it makes sense), e.g.:
import { Min } from 'class-validator';
export class QueryDto {
#Min(1)
readonly limit: number = 50;
}
By the way: Since your #Query will only have string properties, you'll probably want to transform your limit from string to number. Have a look at this answer.
The question has already been answered, but for future reference of people with the same problem...
The class-validator allows you to bypass the validation of certain property (whitelisting) special flags to validate any property.
As the docs:
This will strip all properties that don't have any decorators. If no
other decorator is suitable for your property, you can use #Allow
decorator
e.g:
import {validate, Allow, Min} from "class-validator";
export class Post {
#Allow()
title: string;
#Min(0)
views: number;
nonWhitelistedProperty: number;
}
This is my bootstrap, it works with class-validator:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();

Categories

Resources