Skip to content

Commit

Permalink
Change webpack build mode.
Browse files Browse the repository at this point in the history
Bundle everything even contains the `node_modules`.
  • Loading branch information
samchon committed Nov 20, 2023
1 parent 1ddb7e0 commit 8d487ee
Show file tree
Hide file tree
Showing 5 changed files with 184 additions and 46 deletions.
56 changes: 14 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ Template for a NodeJS Backend Server powered by:

- [Typia](https://typia.io): Superfast/easy validators with only one line
- [NestJS](https://nestjs.com): NodeJS Typescript Backend Framework
- [`@nestia/core`](https://github.com/samchon/nestia): validation decorators 20,000x faster than `class-validator`
- [`@nestia/core`](https://github.com/samchon/nestia): decorators maximum 20,000x faster than `class-validator`
- [`@nestia/sdk`](https://github.com/samchon/sdk): SDK and Swagger Documents generator
- [Prisma](https://www.prisma.io) and [`prisma-markdown`](https://github.com/samchon/prisma-markdown)

Prior, to making this template opensource, I've prepared a couple of backend projects leveraging this template.
Reading this [README.md](https://github.com/samchon/backend) document and traveling below example projects, you may understand how to develop the TypeScript backend server with the [nestia](https://github.com/samchon/nestia) and [safe-typeorm](https://github.com/samchon/safe-typeorm).

- [samchon/bbs-backend](https://github.com/samchon/bbs-backend): Simple Bullet-in Board System
- [samchon/fake-iamport-server](https://github.com/samchon/fake-iamport-server): Fake iamport server, but real SDK
- [samchon/fake-toss-payments-server](https://github.com/samchon/fake-toss-payments-server): Fake toss-payments server, but real SDK

Expand Down Expand Up @@ -92,39 +93,22 @@ Also as you can see from the [package.json](package.json) file, this project req
- https://github.com/features/packages

### 2.2. PostgreSQL
This backend server has adopted PostgreSQL as principle DB.
> ```bash
> bash postgres.sh
>```
>
> If you've installed Docker, then run the script above.
Therefore, to mount this backend server on your local machine, you've to install the PostgreSQL v14. Also, you've to install the StackBuilder and PostGIS, at the same time. Click the below link and install those PostgreSQL, StackBuilder and PostGIS.
Otherwise, visit below PostgreSQL official site and install it manually.
- https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
- https://postgis.net/workshops/postgis-intro/installation.html
https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
![PostgreSQL installer](assets/images/postgresql-installer.png)
After that, run the `npm run schema <root-account> <password>` command.
![StackBuilder installer](assets/images/stackbuilder-installer.png)
Database schema for BBS backend system would be automatically constructed.
When the installation has been finnished, you'd better to configure `bin` directory of the PostgreSQL as a environment variable PATH. If your operating system is the Windows, the path may be `C:\Program Files\PostgreSQL\14\bin`. Otherwise you're using the MacOS, it would be the `/Applications/Postgres.app/Contents/MacOS/bin`.

After the environmenta variable PATH configuration, connect to the PostgreSQL terminal and create each `db_name` database and `db_schema` schema. Also, create two accounts `db_account_w` and `db_account_r`, grant writable and readonly privileges to them.

Anyway, you can replace below SQL scripts by running the `npm run schema <account> <password>`. Running the npm run schema command, replace the `<account>` and `<password>` words to the root account of the local PostgreSQL server and its password.

```sql
-- CREATE USER
CREATE USER "db_account_w" WITH ENCRYPTED PASSWORD 'your_password';
GRANT "db_account_w" TO postgres;

-- CREATE DB & SCHEMA
CREATE DATABASE "db_name" OWNER "db_account_w";
\connect "db_name";
CREATE SCHEMA "db_schema" AUTHORIZATION "db_account_w";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA "db_schema" TO "db_account_w";

-- READABLE ACCOUNT
CREATE USER "db_account_r" WITH ENCRYPTED PASSWORD 'your_password';
GRANT CONNECT ON DATABASE "db_name" TO "db_account_r";
GRANT USAGE ON SCHEMA "db_schema" TO "db_account_r";
GRANT SELECT ON ALL TABLES IN SCHEMA "db_schema" TO "db_account_r";
```bash
npm run schema postgres root
```
### 2.3. Repository
Expand All @@ -140,7 +124,7 @@ cd backend
# INSTALL DEPENDENCIES
npm install
# START DEVELOPMENT (tsc --watch)
# START DEVELOPMENT
npm run dev
```
Expand Down Expand Up @@ -405,10 +389,7 @@ npm run update real
List of the run commands defined in the [package.json](package.json) are like below:

- `build`: Compile the source code
- `build:api`: Build client SDK libray for the client developers
- `build:models`: Build ORM library
- `dev`: Incremental compilation using the `--watch` option
- `reset:dev`: Restart the dev backend server with DB reset
- `revert`: Revert the backend server to previous commit
- `npm run revert local e245tjfg345tq453tae`
- `npm run revert dev e245tjfg345tq453tae`
Expand All @@ -419,18 +400,9 @@ List of the run commands defined in the [package.json](package.json) are like be
- `npm run start dev`
- `npm run start real`
- `package:api`: Deploy the client SDK library
- `package:models`: Deploy the ORM library
- `start:updator:master`: Start non-distruptive update system (master)
- `start:updator:slave`: Start non-distruptive update system (slave)
- `start:reload`: Restart the backend server
- `stop`: Stop the backend server
- `stop:updator:master`: Stop non-distruptive update system (master)
- `stop:updator:salve`: Stop non-distruptive update system (slave)
- `test`: Start the [Test Automation Program](#33-test-automation-program)
- `test:update`: Test the non-distruptive update system
- `update`: Start the non-distruptive update
- npm run update dev
- npm run update real

### 5.2. Github Action
[![Build Status](https://github.com/samchon/backend/workflows/build/badge.svg)](https://github.com/samchon/backend/actions?query=workflow%3Abuild)
Expand Down
13 changes: 9 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"test": "node bin/test",
"test:update": "node bin/test/manual/update",
"test:webpack": "npm run webpack && node bin/test/webpack",
"------------------------BUILDS------------------------": "",
"build": "npm run build:sdk && npm run build:main && npm run build:test",
"build:api": "rimraf packages/api/lib && nestia sdk && tsc -p packages/api/tsconfig.json",
Expand All @@ -20,13 +21,13 @@
"prettier": "prettier src --write && prettier test --write",
"------------------------WEBPACK------------------------": "",
"webpack": "rimraf dist && npm run build:prisma && webpack",
"webpack:prune": "npm ci --omit=dev --ignore-scripts && npm run build:prisma",
"webpack:start": "node dist/server",
"webpack:start:updator:master": "node dist/updator-master",
"webpack:start:updator:slave": "node dist/updator-slave",
"------------------------DEPLOYS------------------------": "",
"package:api": "npm run build:api && cd packages/api && npm publish",
"start": "node lib/executable/server",
"start:swagger": "ts-node src/executable/swagger.ts",
"start:updator:master": "node lib/executable/updator-master",
"start:updator:slave": "node lib/executable/updator-slave",
"schema": "node lib/executable/schema",
Expand Down Expand Up @@ -57,6 +58,7 @@
"@nestia/sdk": "^2.3.9",
"@trivago/prettier-plugin-sort-imports": "^3.3.0",
"@types/cli": "^0.11.19",
"@types/express": "^4.17.21",
"@types/inquirer": "^8.2.5",
"@types/jsonwebtoken": "^9.0.4",
"@types/node": "^18.11.0",
Expand All @@ -66,35 +68,38 @@
"@typescript-eslint/parser": "^5.26.0",
"chalk": "^4.1.2",
"cli": "^1.0.1",
"copy-webpack-plugin": "^11.0.0",
"eslint-plugin-deprecation": "^1.4.1",
"express": "^4.18.2",
"inquirer": "^8.2.5",
"nestia": "^5.0.2",
"pm2": "^4.5.6",
"prettier": "^2.6.2",
"prettier-plugin-prisma": "^5.0.0",
"rimraf": "^3.0.2",
"sloc": "^0.2.1",
"swagger-ui-express": "^5.0.0",
"ts-loader": "^9.5.0",
"ts-node": "^10.9.1",
"ts-patch": "^3.0.2",
"typescript": "^5.2.2",
"typescript-transform-paths": "^3.4.6",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-node-externals": "^3.0.0"
"write-file-webpack-plugin": "^4.5.1"
},
"dependencies": {
"@nestia/core": "^2.3.9",
"@nestjs/common": "^10.2.8",
"@nestjs/core": "^10.2.8",
"@nestjs/platform-fastify": "^10.2.8",
"@prisma/client": "^5.3.1",
"@prisma/client": "^5.6.0",
"dotenv": "^16.3.1",
"dotenv-expand": "^10.0.0",
"git-last-commit": "^1.0.0",
"jsonwebtoken": "^9.0.2",
"mutex-server": "^0.3.1",
"prisma": "^5.3.1",
"prisma": "^5.6.0",
"prisma-markdown": "^1.0.7",
"source-map-support": "^0.5.19",
"tstl": "^2.5.13",
Expand Down
28 changes: 28 additions & 0 deletions src/executable/swagger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import cp from "child_process";
import express from "express";

const execute = (command: string): void => {
console.log(`\n$ ${command}\n`);
cp.execSync(command, { stdio: "inherit" });
};

const main = async (): Promise<void> => {
if (!process.argv.some((str) => str === "--skipBuild"))
execute("npm run build:swagger");

const docs = await import("../../packages/api/swagger.json" as any);

const app = express();
const swaggerUi = require("swagger-ui-express");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(docs));
app.listen(37810);

console.log("\n");
console.log("-----------------------------------------------------------");
console.log("\n Swagger UI Address: http://127.0.0.1:37810/api-docs \n");
console.log("-----------------------------------------------------------");
};
main().catch((exp) => {
console.log(exp);
process.exit(-1);
});
51 changes: 51 additions & 0 deletions test/webpack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { DynamicExecutor } from "@nestia/e2e";
import cp from "child_process";
import fs from "fs";
import { sleep_for } from "tstl";

import { MyConfiguration } from "../src/MyConfiguration";
import MyApi from "../src/api";

const webpackTest = async (): Promise<void> => {
if (fs.existsSync(MyConfiguration.ROOT + "/dist/server.js") === false)
throw new Error("Run npm run webpack command first.");

// START BACKEND SERVER
const backend = cp.fork("server.js", {
cwd: `${MyConfiguration.ROOT}/dist`,
});
await sleep_for(2_500);

// DO TEST
const connection: MyApi.IConnection = {
host: `http://127.0.0.1:${MyConfiguration.API_PORT()}`,
};
const report: DynamicExecutor.IReport = await DynamicExecutor.validate({
prefix: "test",
parameters: () => [
{
host: connection.host,
encryption: connection.encryption,
},
],
})(__dirname + "/features");

backend.kill();

// REPORT EXCEPTIONS
const exceptions: Error[] = report.executions
.filter((exec) => exec.error !== null)
.map((exec) => exec.error!);
if (exceptions.length === 0) {
console.log("Success");
console.log("Elapsed time", report.time.toLocaleString(), `ms`);
} else {
for (const exp of exceptions) console.log(exp);
console.log("Failed");
console.log("Elapsed time", report.time.toLocaleString(), `ms`);
}
};
webpackTest().catch((exp) => {
console.log(exp);
process.exit(-1);
});
82 changes: 82 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const path = require("path");

const CopyWebpackPlugin = require("copy-webpack-plugin");
const WriteFilePlugin = require("write-file-webpack-plugin");
const { IgnorePlugin } = require("webpack");

const lazyImports = [
"@fastify/static",
"@fastify/view",
"@nestjs/microservices",
"@nestjs/websockets",
"class-transformer",
"class-validator",
];

// @reference https://tech-blog.s-yoshiki.com/entry/297
module.exports = {
// CUSTOMIZE HERE
entry: {
server: "./src/executable/server.ts",
"updator-master": "./src/executable/updator-master.ts",
"updator-slave": "./src/executable/updator-slave.ts",
},
output: {
path: path.join(__dirname, "dist"),
filename: "[name].js",
},
optimization: {
minimize: true,
},

// JUST KEEP THEM
mode: "production",
target: "node",
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: "ts-loader",
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: ".env",
to: "[name][ext]",
},
{
from: "package.json",
to: "[name][ext]",
},
{
from: "./node_modules/.prisma/client/*.node",
to: () => Promise.resolve("[path][name][ext]"),
},
{
from: "./node_modules/ws/**/*.*",
to: () => Promise.resolve("[path][name][ext]"),
},
],
}),
new WriteFilePlugin(),
new IgnorePlugin({
checkResource: (resource) => {
if (lazyImports.some((modulo) => resource.startsWith(modulo))) {
try {
require.resolve(resource);
} catch (err) {
return true;
}
}
return false;
},
}),
],
};

0 comments on commit 8d487ee

Please sign in to comment.