Skip to content

Commit

Permalink
Merge pull request #1103 from samchon/feat/request-body-optional
Browse files Browse the repository at this point in the history
Fix #1094: skip validation when no request body
  • Loading branch information
samchon authored Nov 11, 2024
2 parents d45d37d + 8e66379 commit 972fa92
Show file tree
Hide file tree
Showing 87 changed files with 1,096 additions and 660 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.1",
"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.1",
"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.1",
"@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.1",
"@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));
1 change: 0 additions & 1 deletion packages/core/src/programmers/PlainBodyProgrammer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ const validate = (metadata: Metadata): string[] => {
.reduce((a, b) => a + b, 0);
if (expected === 0 || expected !== metadata.size())
insert(`only string type is allowed`);
if (metadata.isRequired() === false) insert(`do not allow undefindable type`);
if (metadata.nullable === true) insert(`do not allow nullable type`);
else if (metadata.any === true) insert(`do not allow any type`);

Expand Down
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/editor/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/editor",
"version": "0.7.1",
"version": "0.8.0",
"typings": "lib/index.d.ts",
"main": "lib/index.js",
"module": "lib/index.mjs",
Expand Down Expand Up @@ -34,7 +34,7 @@
"homepage": "https://nestia.io",
"dependencies": {
"@mui/material": "^5.15.6",
"@nestia/migrate": "^0.19.0",
"@nestia/migrate": "^0.20.0",
"@stackblitz/sdk": "^1.11.0",
"js-yaml": "^4.1.0",
"prettier": "^3.3.3",
Expand Down
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.1",
"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"
}
}
111 changes: 111 additions & 0 deletions packages/migrate/assets/input/v3.1/body-optional.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
{
"openapi": "3.1.0",
"servers": [
{
"url": "https://github.com/samchon/nestia",
"description": "insert your server url"
}
],
"info": {
"version": "3.19.0-dev.20241111",
"title": "@samchon/nestia-test",
"description": "Test program of Nestia",
"license": {
"name": "MIT"
}
},
"paths": {
"/body/optional/json": {
"post": {
"tags": [],
"parameters": [],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/IBodyOptional"
}
}
},
"required": false
},
"responses": {
"201": {
"description": "",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/IBodyOptional"
}
}
}
}
}
}
},
"/body/optional/plain": {
"post": {
"tags": [],
"parameters": [],
"requestBody": {
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
},
"required": false
},
"responses": {
"201": {
"description": "",
"content": {
"application/json": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/health": {
"get": {
"tags": [],
"parameters": [],
"responses": {
"200": {
"description": "",
"content": {
"application/json": {}
}
}
}
}
}
},
"components": {
"schemas": {
"IBodyOptional": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"value": {
"type": "number"
}
},
"required": [
"id",
"value"
]
}
}
},
"tags": [],
"x-samchon-emended": true
}
6 changes: 3 additions & 3 deletions packages/migrate/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/migrate",
"version": "0.19.0",
"version": "0.20.0",
"description": "Migration program from swagger to NestJS",
"typings": "lib/index.d.ts",
"main": "lib/index.js",
Expand Down Expand Up @@ -38,9 +38,9 @@
"homepage": "https://nestia.io",
"devDependencies": {
"@nestia/benchmark": "^0.2.3",
"@nestia/core": "^3.18.0",
"@nestia/core": "^3.19.1",
"@nestia/e2e": "^0.7.0",
"@nestia/fetcher": "^3.18.0",
"@nestia/fetcher": "^3.19.1",
"@nestjs/common": "^10.3.8",
"@nestjs/core": "^10.3.8",
"@nestjs/platform-express": "^10.3.8",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export namespace MigrateApiFunctionProgrammer {
ts.factory.createTypeReferenceNode(
`${route.accessor.at(-1)!}.Input`,
),
(route.body.type === "application/json" ||
route.body.type === "text/plain") &&
route.operation().requestBody?.required === false
? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
: undefined,
),
]
: []),
Expand Down
Loading

0 comments on commit 972fa92

Please sign in to comment.