Skip to content

Commit

Permalink
Fix #1094: skip validation when no request body
Browse files Browse the repository at this point in the history
  • Loading branch information
samchon committed Nov 11, 2024
1 parent f9fd2cc commit 9243a2c
Show file tree
Hide file tree
Showing 61 changed files with 862 additions and 415 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"private": true,
"name": "@nestia/station",
"version": "3.19.0-dev.20241111",
"version": "3.19.0-dev.20241112",
"description": "Nestia station",
"scripts": {
"build": "node build/index.js",
Expand Down
6 changes: 3 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/core",
"version": "3.19.0-dev.20241111",
"version": "3.19.0-dev.20241112",
"description": "Super-fast validation decorators of NestJS",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
Expand Down Expand Up @@ -36,7 +36,7 @@
},
"homepage": "https://nestia.io",
"dependencies": {
"@nestia/fetcher": "^3.19.0-dev.20241111",
"@nestia/fetcher": "^3.19.0-dev.20241112",
"@nestjs/common": ">=7.0.1",
"@nestjs/core": ">=7.0.1",
"@samchon/openapi": "^1.2.2",
Expand All @@ -53,7 +53,7 @@
"ws": "^7.5.3"
},
"peerDependencies": {
"@nestia/fetcher": ">=3.19.0-dev.20241111",
"@nestia/fetcher": ">=3.19.0-dev.20241112",
"@nestjs/common": ">=7.0.1",
"@nestjs/core": ">=7.0.1",
"reflect-metadata": ">=0.1.12",
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/decorators/PlainBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { FastifyRequest } from "fastify";
import { assert } from "typia";

import { get_text_body } from "./internal/get_text_body";
import { is_request_body_undefined } from "./internal/is_request_body_undefined";
import { validate_request_body } from "./internal/validate_request_body";

/**
Expand Down Expand Up @@ -52,7 +53,12 @@ export function PlainBody(
const request: express.Request | FastifyRequest = context
.switchToHttp()
.getRequest();
if (!isTextPlain(request.headers["content-type"]))
if (
is_request_body_undefined(request) &&
(checker ?? (() => null))(undefined as any) === null
)
return undefined;
else if (!isTextPlain(request.headers["content-type"]))
throw new BadRequestException(`Request body type is not "text/plain".`);
const value: string = await get_text_body(request);
if (checker) {
Expand Down
5 changes: 4 additions & 1 deletion packages/core/src/decorators/TypedBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { FastifyRequest } from "fastify";
import { assert, is, misc, validate } from "typia";

import { IRequestBodyValidator } from "../options/IRequestBodyValidator";
import { is_request_body_undefined } from "./internal/is_request_body_undefined";
import { validate_request_body } from "./internal/validate_request_body";

/**
Expand Down Expand Up @@ -35,7 +36,9 @@ export function TypedBody<T>(
const request: express.Request | FastifyRequest = context
.switchToHttp()
.getRequest();
if (isApplicationJson(request.headers["content-type"]) === false)
if (is_request_body_undefined(request) && checker(undefined as T) === null)
return undefined;
else if (isApplicationJson(request.headers["content-type"]) === false)
throw new BadRequestException(
`Request body type is not "application/json".`,
);
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/decorators/internal/is_request_body_undefined.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type express from "express";
import type { FastifyRequest } from "fastify";

/**
* @internal
*/
export const is_request_body_undefined = (
request: express.Request | FastifyRequest,
): boolean =>
request.headers["content-type"] === undefined &&
(request.body === undefined ||
(typeof request.body === "object" &&
request.body !== null &&
Object.keys(request.body).length === 0));
88 changes: 5 additions & 83 deletions packages/core/tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -1,85 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"DOM",
"ES2015"
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "../../test/node_modules/@nestia/core/lib", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
"noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
"types": [
"node",
"reflect-metadata"
], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"stripInternal": true,

/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"plugins": [
{
"transform": "typia/lib/transform",
"functional": true,
}
],
"newLine": "LF",
},
"include": ["src"]
}
"target": "ES2015",
"outDir": "../../test/node_modules/@nestia/core/lib"
}
}
4 changes: 2 additions & 2 deletions packages/fetcher/package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "@nestia/fetcher",
"version": "3.19.0-dev.20241111",
"version": "3.19.0-dev.20241112",
"description": "Fetcher library of Nestia SDK",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"scripts": {
"build": "rimraf lib && tsc",
"dev": "npm run build -- --watch",
"dev": "tsc -p tsconfig.test.json --watch",
"eslint": "eslint src",
"eslint:fix": "eslint src --fix"
},
Expand Down
4 changes: 3 additions & 1 deletion packages/fetcher/src/internal/FetcherBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,15 @@ export namespace FetcherBase {
const headers: Record<string, IConnection.HeaderValue | undefined> = {
...(connection.headers ?? {}),
};
if (input !== undefined)
if (input !== undefined) {
if (route.request?.type === undefined)
throw new Error(
`Error on ${props.className}.fetch(): no content-type being configured.`,
);
else if (route.request.type !== "multipart/form-data")
headers["Content-Type"] = route.request.type;
} else if (input === undefined && headers["Content-Type"] !== undefined)
delete headers["Content-Type"];

// INIT REQUEST DATA
const init: RequestInit = {
Expand Down
7 changes: 7 additions & 0 deletions packages/fetcher/tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2015",
"outDir": "../../test/node_modules/@nestia/fetcher/lib"
}
}
10 changes: 5 additions & 5 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/sdk",
"version": "3.19.0-dev.20241111",
"version": "3.19.0-dev.20241112",
"description": "Nestia SDK and Swagger generator",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
Expand Down Expand Up @@ -32,8 +32,8 @@
},
"homepage": "https://nestia.io",
"dependencies": {
"@nestia/core": "^3.19.0-dev.20241111",
"@nestia/fetcher": "^3.19.0-dev.20241111",
"@nestia/core": "^3.19.0-dev.20241112",
"@nestia/fetcher": "^3.19.0-dev.20241112",
"@samchon/openapi": "^1.2.2",
"cli": "^1.0.1",
"get-function-location": "^2.0.0",
Expand All @@ -47,8 +47,8 @@
"typia": "^6.12.0"
},
"peerDependencies": {
"@nestia/core": ">=3.19.0-dev.20241111",
"@nestia/fetcher": ">=3.19.0-dev.20241111",
"@nestia/core": ">=3.19.0-dev.20241112",
"@nestia/fetcher": ">=3.19.0-dev.20241112",
"@nestjs/common": ">=7.0.1",
"@nestjs/core": ">=7.0.1",
"reflect-metadata": ">=0.1.12",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export namespace SdkHttpFunctionProgrammer {
[],
undefined,
p.name,
p.metadata.optional
p.metadata.optional === true
? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
: undefined,
project.config.primitive !== false &&
Expand Down
24 changes: 9 additions & 15 deletions packages/sdk/src/transformers/SdkOperationProgrammer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export namespace SdkOperationProgrammer {
),
jsDocTags: p.symbol?.getJsDocTags() ?? [],
description: p.symbol
? CommentFactory.description(p.symbol) ?? null
? (CommentFactory.description(p.symbol) ?? null)
: null,
};
};
Expand All @@ -61,15 +61,20 @@ export namespace SdkOperationProgrammer {
}): IOperationMetadata.IParameter => {
const symbol: ts.Symbol | undefined =
props.context.checker.getSymbolAtLocation(props.parameter);
const common: IOperationMetadata.IResponse = writeType({
const common: IOperationMetadata.IResponse = writeResponse({
context: props.context,
generics: props.generics,
type:
props.context.checker.getTypeFromTypeNode(
props.parameter.type ?? TypeFactory.keyword("any"),
) ?? null,
required: props.parameter.questionToken === undefined,
});
const optional: boolean = props.parameter.questionToken !== undefined;
if (common.primitive.success)
common.primitive.data.metadata.optional = optional;
if (common.resolved.success)
common.resolved.data.metadata.optional = optional;

return {
...common,
name: props.parameter.name.getText(),
Expand All @@ -79,21 +84,10 @@ export namespace SdkOperationProgrammer {
};
};

const writeResponse = (props: {
context: ISdkOperationTransformerContext;
generics: WeakMap<ts.Type, ts.Type>;
type: ts.Type | null;
}): IOperationMetadata.IResponse =>
writeType({
...props,
required: true,
});

const writeType = (p: {
const writeResponse = (p: {
context: ISdkOperationTransformerContext;
generics: WeakMap<ts.Type, ts.Type>;
type: ts.Type | null;
required: boolean;
}): IOperationMetadata.IResponse => {
const analyzed: ImportAnalyzer.IOutput = p.type
? ImportAnalyzer.analyze(p.context.checker, p.generics, p.type)
Expand Down
Loading

0 comments on commit 9243a2c

Please sign in to comment.