Files
yara724api/src/main.ts
2026-05-31 15:03:46 +03:30

94 lines
2.6 KiB
TypeScript

import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "./app.module";
import { ConfigService } from "@nestjs/config";
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: true,
});
app.enableCors({
origin: "*",
methods: "GET, PUT, POST, DELETE, PATCH, OPTIONS",
allowedHeaders: "Content-Type, Authorization",
});
const configService = app.get(ConfigService);
const isDevelopment = configService.get<string>("NODE_ENV") === "development";
if (isDevelopment) {
app.use("/docs", (req, res, next) => {
const authHeader = req.headers.authorization;
const challenge = () => {
res.setHeader("WWW-Authenticate", 'Basic realm="Swagger"');
res.status(401).send("Unauthorized");
};
if (!authHeader?.startsWith("Basic ")) {
return challenge();
}
try {
const base64 = authHeader.split(" ")[1];
const [username, ...rest] = Buffer.from(base64, "base64")
.toString("utf8")
.split(":");
const password = rest.join(":");
const expectedUser = configService.get<string>("SWAGGER_USER_DEV", "");
const expectedPassword = configService.get<string>(
"SWAGGER_PASSWORD_DEV",
"",
);
if (username !== expectedUser || password !== expectedPassword) {
return challenge();
}
next();
} catch {
return challenge();
}
});
const config = new DocumentBuilder()
.setTitle("yara724-backend")
.setVersion("1.0.0")
.addServer(process.env.BASE_URL_DEV + "/api")
.addServer("http://192.168.20.170:9001")
.addServer("https://user.yara724.com/api")
.addServer("http://localhost:9001")
.addBearerAuth()
.build();
const docs = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("docs", app, docs, {
swaggerOptions: {
persistAuthorization: true,
docExpansion: "none",
ui: isDevelopment ? true : false,
raw: isDevelopment ? true : false,
tagsSorter: (a: string, b: string) => {
const priority: Record<string, number> = {
user: 0,
actor: 1,
};
const pa = priority[a] ?? 100;
const pb = priority[b] ?? 100;
if (pa !== pb) return pa - pb;
return a.localeCompare(b);
},
},
});
}
await app.listen(process.env.PORT);
}
void bootstrap();