1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

駆け出しエンジニアがExpress.jsとSwaggerを使ってみました!

Posted at

こんにちは!私は、ここ最近Web開発の世界に飛び込んだ1年目のエンジニアです。仕事でSwaggerに触れたことがきっかけで、プライベートの時間にAPIドキュメンテーションの作成に挑戦したときの記録を記事化しました。

今回はExpress.jsを使ったAPI開発、SwaggerでのAPIドキュメンテーション生成に挑戦したので、その経験をシェアしたいと思います。

なんとなくでも参考になれば嬉しいですし、もし何かアドバイスがあればぜひ教えてください!

// 各種モジュールをインポート
import express from "express";
import userIdCheckRouter from "./userIdCheck";
import swaggerJSDoc from "swagger-jsdoc";
import { serve, setup } from "swagger-ui-express";

// Expressアプリを初期化
const app = express();
// 環境変数からポート番号と許可されたIPアドレスを取得
const PORT = Number(process.env.PORT as string);
const ALLOWED_IPS = process.env.ALLOWED_IPS ? (process.env.ALLOWED_IPS as string).split(',') : undefined;

// リバースプロキシからの接続を信頼(リバースプロキシを使用している場合)
app.set('trust proxy', true);

// 許可されたIPアドレスからのアクセスのみを許可
if (ALLOWED_IPS) {
	app.use((req, res, next) => {
		const clientIp = (req.headers['x-forwarded-for'] as string)?.split(',')[0].trim() || req.ip;
		if (!ALLOWED_IPS.includes(clientIp)) {
			return res.status(403).json({ message: "Your IP address is not allowed." });
		}
		next();
	});
}

// JSONを受け取れるようにする
app.use(express.json());

// ルートを設定
/**
 * @swagger
 * /api/user/userIdCheck/{userId}:
 *   get:
 *     description: Check user ID
 *     parameters:
 *       - name: userId
 *         in: path
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: success
 */
app.use("/api/user", userIdCheckRouter);

// Swaggerの設定
const options = {
	definition: {
		openai: "3.0.0",
		info: {
			title: "Express API with Swagger",
			version: "1.0.0",
		},
	},
	apis: ["./src/api/*.ts"],
};
const specs = swaggerJSDoc(options);
app.use("/api-docs", serve, setup(specs));

// サーバを起動
app.listen(PORT || 3000, () => {
	console.log("Server is running on port 3000");
});

これでコードの完成です!

特に大変だったポイントは以下の3つです:

1. リストアクセス元IPの制御: 特定のIPからのリクエストのみを許可するよう設定しました。

2. Swaggerを用いたAPIドキュメンテーションの自動生成: 実務ではNext.jsによるドキュメント生成を行っているのですが、使わない場合はこういった実装法になるのですね。一つのやり方として覚えておこうと思います!

まだまだ学びたいことは山積みですが、一歩ずつ進んでいこうと思います。フィードバックもぜひお待ちしています!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?