NestJs validation pipe not working properly - javascript

I have the following DTO class in my project:
import { IsNotEmpty, IsString } from "class-validator";
export class CreateDomainDTO {
#IsString()
codigo_website: string;
#IsString()
website_name: string
}
I have NestJs default validation pipe applied for my entire project:
main.ts file
However, NestJs is messing up the validation and returning a response that doesn't make sense to me.
When I send this payload in my request:
{
"codigo_website": "lipgMEjz4altEmeb9hms",
"website_name": "Modelo 2.1"
}
I get the following validation error:
"property {\"codigo_website\":\"lipgMEjz4altEmeb9hms\",\"website_name\":\"Modelo 2.1\"} should not exist","codigo_website must be a string","website_name must be a string"
It is considering my entire body as being a single property and I don't have any idea why. Plus, this error seems to only happen in production, but within a few days ago it was working fine.
Does anyone have any idea why this is happening? Should I create a custom validation pipe?
Grateful in advance.

If you're on postman, make sure the body is raw and select JSON. If using frontend API, set the content-type to application/json.

Related

SyntaxError: ambiguous indirect export: default Error when importing my own class

I have written a validation class and want to include it in my VueJS 3 project. Unfortunately I get the following error: SyntaxError: ambiguous indirect export: default
This is my code:
// ..classes/formValidationClass.js
export class FormValidator {
...
}
// some vue file with a form
import FormValidation from "..classes/formValidationClass"
export default {...}
Question:
What does this error mean and what do I have to do to correct the error?
Use brackets {} around your import Name
// ..classes/formValidatorClass.js // Comment: => suggestion change your file name to similar your class name
export class FormValidator {
...
}
// some vue file with a form
// import FormValidation from "..classes/formValidationClass"
import { FormValidator as FormValidation} from "../classes/formValidatorClass"; // Comment: => use brackets around your import name. if you want use FormValidation you can use also a alias (`originalName as newName`)
export default {...}
I found that none of the tsconfig, package.json fixes would never work for me. Hopefully the following helps someone in the future.
I was consistently getting this error when working with Vite projects and not Webpack projects. I would not be able to import anything, named or otherwise.
On one Svelte code base I ran the Svelte CLI sync command and it mentioned a type import was breaking the importsNotUsedAsValues or preserveValueImports and that I should explicitly mark the import as a type.
The import statement in question:
import { TUser } from '../models/Users/Users';
TUser exported as:
export type TUser = { ... }
Errors
Would cause the following errors:
Error: This import is never used as a value and must use 'import type' because 'importsNotUsedAsValues' is set to 'error'. (ts)
Error: 'TUser' is a type and must be imported using a type-only import when 'preserveValueImports' and 'isolatedModules' are both enabled. (ts)
Solution
Doing the following fixed the issue for me.
import type { TUser } from '../models/Users/Users';
My story: WebStorm generated .js files right next to .ts files (because I once enabled the Recompile on changes option), so my app tried to import from .js files instead of .ts one. That was the reason for the import problems.
This is the compiled code on the local dev server:
For the sake of helping anyone bumping into this error and arriving at this page, the word default in export default function myFunction() can cause this error. Or in other words: remove the word default may help.
In my case I had the curly braces where I shouldn't have. I had a JSON file and import { users } from ... where instead I should have no curly braces like so:
import users from './users.json';
console.log("users", users);

How do I use TypeScript typing information from a Node.js package?

I've read a ton of different variations of this same question, but I just can't wrap my mind around it. I'm using the websocket module (which I've used many times before without TypeScript) and I can't figure out how to type my variables?
I have a function that takes in a WebSocketConnection object, but when I give it the type WebSocketConnection I get a "Cannot find name 'WebSocketConnection'" from TypeScript.
I've installed the #types/websocket package and I can see the index.d.ts file with all the type definitions in it located in ./node_modules/#types/websocket/index.d.ts relative to my tsconfig.json file...
I've tried adding the "typeRoots" option to the tsconfig.json file, as well as "types". I've tried many combination of values but as far as I can tell leaving them off entirely is a better bet, so I've tried that as well. I've also tried many variations of importing data from both the .d.ts file and also the package itself, with no luck of course.
I tried using /// <reference path="node_modules/#types/websocket/index.d.ts" /> also with no luck.
I looked in the .d.ts file and found a very clear declaration of an interface called IStringified that looked like this:
export interface IStringified {
toString: (...args: any[]) => string;
}
So I tried to access IStringified and I'm still getting the same "Cannot find name 'IStringified'" error.
I'm probably just being really dumb and missing something plainly obvious, but any pointers or advice would be much appreciated! What in the world am I doing wrong?
Types of installed packages are not available globally. They must be imported into each file in order to use them. Don't mess with typeroots or triple slash directives at all, that will only make things worse.
In this particular case, the module exports a connection class, which is probably what you want. It's unfortunate name means to make it it look the class constructor that it really is you should probably rename in on import:
import {
server as WebSocketServer,
connection as WebSocketConnection,
} from 'websocket'
And now you can do:
const wsServer = new WebSocketServer({ httpServer: server });
wsServer.on('request', function(request) {
var connection = request.accept('echo-protocol', request.origin);
doSomethingWithWsConnection(connection) // works
});
function doSomethingWithWsConnection(connection: WebSocketConnection) {
//...
}
Typesafe example on TS playground
So I tried to access IStringified and I'm still getting the same "Cannot find name 'IStringified'" error.
You import the type, then use the type:
import { IStringified } from 'websocket'
const foo: IStringified = { toString: () => 'asdf' }
Playground

Cannot load my JSON file: Http failure during parsing for JSON

I am attempting to load valid json but I am getting the error:
stackblitz
Http failure during parsing for ... .json
recipe.component.ts
url = '../../files/recipes.json';
recipes;
constructor(private fileService: FileLoaderService) {}
ngOnInit() {
this.fileService.getData(this.url).subscribe(res => console.log(res));
}
file-loader.service.ts
constructor(private http: HttpClient) { }
getData(url: string): Observable<any> {
return this.http.get(url);
}
What you have is not a valid JSON file. epascarello's answer tells you how to convert it to valid JSON, but another option is to just import the data directly.
Change the .json file extension to .ts
In your component, add import {recipes} from '../../files/recipes'
You've got your data! No need to mess around with http requests.
Having the export
export const recipes = [
{...}
]
makes it not a valid json document. Do not use export, remove it
JSON file should just be the json.
[
{...}
]
Couple this wrong and missing here:
This is not a valid JSON file (in the stackblitz). This is a constant which you can just import using a normal typescript import. If you want to load it using http, you should remove the export const recipes from the file
You should move the files folder to the assets folder of the project, this way the file can be loaded from the http server.
I spent a while ripping my hair out today (new to writing in StackBlitz). and even tried what was marked as answer on this thread, with no luck. Anyhow, the key seemed to be adding the .json file to the assets folder. Here's the link that finally got me immediate success. Hope that helps someone else keep their hair in tact. :-)
I've been asked to add code snippet, but not really too much to add, so I created a StackBlitz example that can be viewed, if desired. However, basically it all boils down to this: in StackBlitz when you're loading a local .json file, you do the same thing you normally would...except you ABSOLUTELY put that .json file in the "assets" folder (if you don't have one, create one)
this.http.get('/assets/user.json')
I added a StackBlitz example here

Clever way to define a GraphQL Query/Mutation with JavaScript

Maybe it's just me but I´m pretty much annoyed of defining my GraphQL Queries/Mutations with backticks. The problem here is that, if I have to apply some changes to the query string, it's pretty annoying to reformat the string inside the backticks.
Is there a clever way to define a more readable and maintainable GraphQL Query/Mutation with JavaScript? It's also hard to find missing brackets when the query string is messed up.
I am doing like this right now:
import gql from 'graphql-tag';
export const fancyMutation = gql`
mutation($id: ID!)
{
delete_something(id:$id) {
id
foo
bar
}
}
`;
You can also put your queries into their own files, e.g. with a .graphql or .gql file extension, and use the graphql-tag/loader to load the query from the file where you need it.
Given this query in its own file:
query CurrentUserForLayout {
currentUser {
login
avatar_url
}
}
With webpack you would need the following configuration:
module: {
rules: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
},
],
},
Then you could load it like that:
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import currentUserQuery from './currentUser.graphql';
class Profile extends Component { ... }
Profile.propTypes = { ... };
export default graphql(currentUserQuery)(Profile)
Update:
You can also have multiple queries in one file:
query MyQuery1 {
...
}
query MyQuery2 {
...
}
You can then load them like this:
import { MyQuery1, MyQuery2 } from 'query.gql'
Other than that I don't know about other options to define queries inline. The backticks aren't graphql specific. It just uses the es6 template tags like e.g. styled components does to define inline css. Your only option is to get an IDE that can recognize graphql queries to provide editing help and code highlighting. IntelliJ Editors (IDEA, WebStorm, PyCharm) have a plugin for that like #Victor Vlasenko pointed out.
JS GraphQL WebStorm plugin starting from version 1.4.1 supports embedded GraphQL strings.
From the WebStorm menu select File -> Settings -> Plugins -> Browse repositories and find JS GraphQL plugin. Check that you have at least version 1.4.1 of this plugin installed.
When installed it should highlight braces and let you reformat GraphQL inside string by selecting code block and choosing Code -> Reformat code from IDE menu.
This plugin project page is located here:
https://github.com/jimkyndemeyer/js-graphql-intellij-plugin

TypeScript Error TS 2094/2095 property 'x' does not exist on value of type 'JQuery'

Hey I've been trying to figure this out but it seems to be really weird. I know to include the .d.ts file in the top. I recently upgraded ts from 0.831 to 0.95. Did all the necessary changes and still getting errors.
More specifically, I'm working with JQGrid and there is no typed file in the Definitely Typed repo so I created one. Here is the definition file.
/// <reference path="..\Imports\jquery-1.8.d.ts" />
interface JQuery {
jqGrid(options?: JQGrid.JQGrid_Options): JQuery;
fluidGrid(options: JQGrid.FluidGrid_Options): JQuery;
}
declare module JQGrid {
export interface JQGrid_ColModel {
...
}
export interface JQGrid_Options {
...
}
interface FluidGrid_Options {
...
}
}
The '...' are just options.
I'm getting "error TS2094: The property 'jqGrid' does not exist on value of type 'JQuery'" from the line of code
$("#prospectsByReferrer").jqGrid(this.gridOptions);
and "error TS2095: Could not find symbol 'JQGrid'" from code
private gridOptions: JQGrid.JQGrid_Options;
The full code is
/// <reference path="..\..\Scripts\Base\ViewModelBase.ts" />
/// <reference path="..\..\Scripts\Imports\JQGrid.d.ts" />
module Biz.Views {
export class ProspectsTab extends ViewModelBase{
private gridOptions: JQGrid.JQGrid_Options; <--error TS2095
private _businessId: number;
private _isInitialized: boolean = false;
constructor () {
this.gridOptions = {};
$("#prospectsByReferrer").jqGrid(this.gridOptions); <---error TS2094
}
What I'm not getting is why TS can't see this typed when it's declared above. What am I not doing right? I've ran out of ideas that includes some typing. Thanks for your time.
By the way, I'm using Visual Studios 2012 and intellisense doesn't give me a red squiggly. It's only my console that outputs the error.
I expect this is a stupid answer but it happens to me all the time.. I'm also using VS and typescript.
Did you forget to include the JQGrid.js file in your HTML document?
The TS compiler seemed to flip out when I had special characters in my ts file. I comment code from Word and Word has weird characters that they format themselves such as ..., -, etc. Removing these 'weird' characters allowed the compilation to happen again.

Categories

Resources