Skip to content

Commit

Permalink
process.env の取得処理を共通関数化
Browse files Browse the repository at this point in the history
  • Loading branch information
SaekiTominaga committed Jan 19, 2025
1 parent c434137 commit 4d05044
Show file tree
Hide file tree
Showing 13 changed files with 75 additions and 44 deletions.
15 changes: 15 additions & 0 deletions astro/src/+util/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* `process.env` の値を取得する
*
* @param key - キー
*
* @returns
*/
export const env = (key: string): string => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`process.env["${key}"] not defined`);
}

return value;
};
7 changes: 2 additions & 5 deletions astro/src/+util/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'node:path';
import type { AstroGlobal } from 'astro';
import * as dotenv from 'dotenv';
import Log4js from 'log4js';
import { env } from './env.js';

interface Options {
dev: boolean;
Expand All @@ -24,11 +25,7 @@ export const init = (Astro: AstroGlobal, options: Options): { logger: Log4js.Log
});

/* Logger */
const loggerFilePath = process.env['LOGGER'];
if (loggerFilePath === undefined) {
throw new Error('Logger file path not defined');
}
Log4js.configure(loggerFilePath);
Log4js.configure(env('LOGGER'));
const logger = Log4js.getLogger(Astro.url.pathname);

return { logger };
Expand Down
7 changes: 2 additions & 5 deletions astro/src/pages/admin/crawler-news/data.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import Layout from '@layouts/Admin.astro';
import CrawlerNewsDataDao from '@dao/CrawlerNewsDataDao.js';
import HttpResponseUtil from '@util/HttpResponse.js';
import { env } from '@util/env.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit, getPageUrl } from '@util/ssr.js';
import type { StructuredData } from '@type/types.js';
Expand Down Expand Up @@ -31,11 +32,7 @@ const requestQuery: RequestQuery = {
action_delete: RequestUtil.boolean(requestBody?.get('actiondel')),
};
const sqlite = process.env['SQLITE_CRAWLER'];
if (sqlite === undefined) {
throw new Error('SQLite crawler not defined');
}
const dao = new CrawlerNewsDataDao(sqlite);
const dao = new CrawlerNewsDataDao(env('SQLITE_CRAWLER'));
if (requestQuery.action_delete) {
/* 削除 */
Expand Down
7 changes: 2 additions & 5 deletions astro/src/pages/admin/crawler-news/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Layout from '@layouts/Admin.astro';
import H from '@components/H.astro';
import Section from '@components/Section.astro';
import CrawlerNewsDao from '@dao/CrawlerNewsDao.js';
import { env } from '@util/env.js';
import HttpResponseUtil from '@util/HttpResponse.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit, getPageUrl } from '@util/ssr.js';
Expand Down Expand Up @@ -53,11 +54,7 @@ const requestQuery: RequestQuery = {
action_delete: RequestUtil.boolean(requestBody?.get('actiondel')),
};
const sqlite = process.env['SQLITE_CRAWLER'];
if (sqlite === undefined) {
throw new Error('SQLite crawler not defined');
}
const dao = new CrawlerNewsDao(sqlite);
const dao = new CrawlerNewsDao(env('SQLITE_CRAWLER'));
if (requestQuery.action_add) {
/* 登録 */
Expand Down
3 changes: 2 additions & 1 deletion astro/src/pages/admin/crawler-resource/diff.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import fs from 'node:fs';
import { diffLines, type Change as DiffChange } from 'diff';
import Layout from '@layouts/Admin.astro';
import { env } from '@util/env.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit } from '@util/ssr.js';
import type { StructuredData } from '@type/types.js';
Expand Down Expand Up @@ -30,7 +31,7 @@ const diffs: DiffChange[] = [];
const fileList: string[] = [];
if (requestQuery.dir !== null) {
const dir = `${process.env['CRAWLER_RESOURCE_LOG_DIR']}/${requestQuery.dir}`;
const dir = `${env('CRAWLER_RESOURCE_LOG_DIR')}/${requestQuery.dir}`;
if (fs.existsSync(dir)) {
if (requestQuery.diff.length >= 2) {
/* 差分チェック */
Expand Down
7 changes: 2 additions & 5 deletions astro/src/pages/admin/crawler-resource/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Layout from '@layouts/Admin.astro';
import H from '@components/H.astro';
import Section from '@components/Section.astro';
import CrawlerResourceDao from '@dao/CrawlerResourceDao.js';
import { env } from '@util/env.js';
import HttpResponseUtil from '@util/HttpResponse.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit, getPageUrl } from '@util/ssr.js';
Expand Down Expand Up @@ -49,11 +50,7 @@ const requestQuery: RequestQuery = {
action_delete: RequestUtil.boolean(requestBody?.get('actiondel')),
};
const sqlite = process.env['SQLITE_CRAWLER'];
if (sqlite === undefined) {
throw new Error('SQLite crawler not defined');
}
const dao = new CrawlerResourceDao(sqlite);
const dao = new CrawlerResourceDao(env('SQLITE_CRAWLER'));
if (requestQuery.action_add) {
/* 登録 */
Expand Down
3 changes: 2 additions & 1 deletion astro/src/pages/admin/crawler-resource/log.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
import fs from 'node:fs';
import Layout from '@layouts/Admin.astro';
import { env } from '@util/env.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit } from '@util/ssr.js';
import type { StructuredData } from '@type/types.js';
Expand All @@ -26,7 +27,7 @@ const requestQuery: RequestQuery = {
};
if (requestQuery.dir !== null && requestQuery.file !== null) {
const filePath = `${process.env['CRAWLER_RESOURCE_LOG_DIR']}/${requestQuery.dir}/${requestQuery.file}`;
const filePath = `${env('CRAWLER_RESOURCE_LOG_DIR')}/${requestQuery.dir}/${requestQuery.file}`;
/* ソースコード閲覧 */
try {
Expand Down
13 changes: 7 additions & 6 deletions astro/src/pages/contact.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ejs from 'ejs';
import nodemailer from 'nodemailer';
import Layout from '@layouts/W0s.astro';
import HttpResponseUtil from '@util/HttpResponse.js';
import { env } from '@util/env.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit } from '@util/ssr.js';
import type { StructuredData } from '@type/types.js';
Expand Down Expand Up @@ -47,17 +48,17 @@ if (Astro.request.method === 'POST') {
});
const transporter = nodemailer.createTransport({
host: process.env['MAIL_SMTP'],
port: Number(process.env['MAIL_PORT']),
host: env('MAIL_SMTP'),
port: Number(env('MAIL_PORT')),
auth: {
user: process.env['MAIL_USER'],
pass: process.env['MAIL_PASSWORD'],
user: env('MAIL_USER'),
pass: env('MAIL_PASSWORD'),
},
});
const info = await transporter.sendMail({
from: process.env['MAIL_FROM'],
to: process.env['MAIL_TO'],
from: env('MAIL_FROM'),
to: env('MAIL_TO'),
subject: 'w0s.jp 問い合わせ',
html: html,
});
Expand Down
7 changes: 2 additions & 5 deletions astro/src/pages/tokyu/data/history/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Layout from '@layouts/Tokyu.astro';
import H from '@components/H.astro';
import Section from '@components/Section.astro';
import TokyuCarHistoryDao from '@dao/TokyuCarHistoryDao.js';
import { env } from '@util/env.js';
import RequestUtil from '@util/Request.js';
import { init as ssrInit } from '@util/ssr.js';
import type { StructuredData } from '@type/types.js';
Expand Down Expand Up @@ -72,11 +73,7 @@ const requestQuery: RequestQuery = {
output: RequestUtil.string(requestParams.get('out')),
};
const sqlite = process.env['SQLITE_TOKYU_CAR_HISTORY'];
if (sqlite === undefined) {
throw new Error('SQLite tokyu car history not defined');
}
const dao = new TokyuCarHistoryDao(sqlite);
const dao = new TokyuCarHistoryDao(env('SQLITE_TOKYU_CAR_HISTORY'));
const carSeries = await dao.getCarSeries();
Expand Down
4 changes: 3 additions & 1 deletion express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
"scripts": {
"app": "tsx --watch --tsconfig tsconfig.json src/app.ts",
"build": "tsc --project tsconfig.json",
"lint": "eslint src/**/*.ts"
"lint": "eslint src/**/*.ts",
"pretest": "npm run build",
"test": "node --experimental-test-coverage --env-file=../.env.development --test **/*.test.js"
},
"dependencies": {
"@w0s.jp/astro": "*",
Expand Down
13 changes: 3 additions & 10 deletions express/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import HtmlEscape from '@w0s/html-escape';
// @ts-expect-error: ts(7016)
import { handler as ssrHandler } from '@w0s.jp/astro/dist/server/entry.mjs';
import config from './config/express.js';
import { env } from './util/env.js';

/* 設定ファイル読み込み */
dotenv.config({
Expand Down Expand Up @@ -75,11 +76,6 @@ app.use(
}),
async (req, res, next) => {
/* Basic Authentication */
const authFileDirectory = process.env['AUTH_DIRECTORY'];
if (authFileDirectory === undefined) {
throw new Error('Auth file directory not defined');
}

const basic = config.static.authBasic.find((auth) => isMatch(req.url, auth.urls));
if (basic !== undefined) {
const credentials = basicAuth(req);
Expand All @@ -88,7 +84,7 @@ app.use(
const result = (await htpasswd.authenticate({
username: credentials?.name,
password: credentials?.pass,
file: `${authFileDirectory}/${basic.htpasswd}`,
file: `${env('AUTH_DIRECTORY')}/${basic.htpasswd}`,
})) as boolean;

if (!result) {
Expand Down Expand Up @@ -220,10 +216,7 @@ app.use((err: Error, req: Request, res: Response, _next: NextFunction /* eslint-
/**
* HTTP サーバー起動
*/
const port = process.env['PORT'];
if (port === undefined) {
throw new Error('Port not defined');
}
const port = env('PORT');
app.listen(Number(port), () => {
console.info(`Server is running on http://localhost:${port}`);
});
18 changes: 18 additions & 0 deletions express/src/util/env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { strict as assert } from 'node:assert';
import { test } from 'node:test';
import { env } from './env.js';

process.env['TEST_KEY'] = 'foo';

await test('exist key', () => {
assert.equal(env('TEST_KEY'), 'foo');
});

await test('non exist key', () => {
assert.throws(
() => {
env('TEST_KEY2');
},
{ name: 'Error', message: 'process.env["TEST_KEY2"] not defined' },
);
});
15 changes: 15 additions & 0 deletions express/src/util/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* `process.env` の値を取得する
*
* @param key - キー
*
* @returns
*/
export const env = (key: string): string => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`process.env["${key}"] not defined`);
}

return value;
};

0 comments on commit 4d05044

Please sign in to comment.