first commit

This commit is contained in:
ntki72 2024-12-25 14:29:02 +09:00
commit 31b5d6dd6e
19 changed files with 3047 additions and 0 deletions

144
.gitignore vendored Normal file
View File

@ -0,0 +1,144 @@
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
# End of https://www.toptal.com/developers/gitignore/api/node

1
.tool-versions Normal file
View File

@ -0,0 +1 @@
nodejs 22.12.0

17
Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM node:22.12.0-alpine
WORKDIR /app
# パッケージファイルをコピーしてインストール
COPY package*.json ./
RUN npm install
# ソースコードをコピーしてビルド
COPY . .
RUN npm run build
COPY wait-for-it.sh /wait-for-it.sh
RUN chmod +x /wait-for-it.sh
# シェルスクリプトを使って、MySQL サーバーの起動を待機
CMD ["/bin/sh", "/wait-for-it.sh", "db", "3306", "--", "npm", "run", "start"]

11
config/config.js Normal file
View File

@ -0,0 +1,11 @@
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: "mysql"
}
};

33
docker-compose.yml Normal file
View File

@ -0,0 +1,33 @@
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
depends_on:
- db
environment:
NODE_ENV: development
DB_NAME: ${DB_NAME}
DB_USER: ${DB_USER}
DB_PASS: ${DB_PASS}
DB_HOST: db
db:
image: mysql:8.0
volumes:
- db-store:/var/lib/mysql
- ./logs:/var/log/mysql
- ./docker/mysql/my.cnf:/etc/mysql/conf.d/my.cnf
environment:
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASS}
MYSQL_ROOT_PASSWORD: ${DB_PASS}
TZ: ${TZ}
ports:
- ${DB_PORT}:3306
volumes:
db-store:

View File

@ -0,0 +1,31 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Channels', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
youtube_id: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Channels');
}
};

View File

@ -0,0 +1,37 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('LiveSchedules', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
channelId: {
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
start_time: {
type: Sequelize.DATE
},
thumbnail_url: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('LiveSchedules');
}
};

24
models/channel.js Normal file
View File

@ -0,0 +1,24 @@
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Channel extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Channel.init({
name: DataTypes.STRING,
youtube_id: DataTypes.STRING
}, {
sequelize,
modelName: 'Channel',
});
return Channel;
};

43
models/index.js Normal file
View File

@ -0,0 +1,43 @@
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf('.') !== 0 &&
file !== basename &&
file.slice(-3) === '.js' &&
file.indexOf('.test.js') === -1
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;

26
models/liveschedule.js Normal file
View File

@ -0,0 +1,26 @@
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class LiveSchedule extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
LiveSchedule.init({
channelId: DataTypes.INTEGER,
title: DataTypes.STRING,
start_time: DataTypes.DATE,
thumbnail_url: DataTypes.STRING
}, {
sequelize,
modelName: 'LiveSchedule',
});
return LiveSchedule;
};

35
my.cnf Normal file
View File

@ -0,0 +1,35 @@
# MySQLサーバーへの設定
[mysqld]
# 文字コード/照合順序の設定
character-set-server = utf8mb4
collation-server = utf8mb4_bin
# タイムゾーンの設定
default-time-zone = SYSTEM
log_timestamps = SYSTEM
# デフォルト認証プラグインの設定
default-authentication-plugin = mysql_native_password
# エラーログの設定
log-error = /var/log/mysql/mysql-error.log
# スロークエリログの設定
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 5.0
log_queries_not_using_indexes = 0
# 実行ログの設定
general_log = 1
general_log_file = /var/log/mysql/mysql-query.log
# mysqlオプションの設定
[mysql]
# 文字コードの設定
default-character-set = utf8mb4
# mysqlクライアントツールの設定
[client]
# 文字コードの設定
default-character-set = utf8mb4

2541
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
package.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "youtube_live_calendar",
"version": "1.0.0",
"main": "dist/app.js",
"scripts": {
"build": "tsc",
"start": "node dist/app.js"
},
"dependencies": {
"dotenv": "^16.4.7",
"express": "^4.18.2",
"express-basic-auth": "^1.2.0",
"mysql2": "^3.3.3",
"node-cron": "^3.0.0",
"sequelize": "^6.32.1"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/node": "^20.4.2",
"sequelize-cli": "^6.6.2",
"typescript": "^5.2.2"
}
}

25
src/app.ts Normal file
View File

@ -0,0 +1,25 @@
import express from "express";
import sequelize from "./models";
const app = express();
const port = 3000;
app.use(express.json());
// データベース接続テスト
sequelize.authenticate()
.then(() => {
console.log("Database connected successfully!");
})
.catch((err) => {
console.error("Unable to connect to the database:", err);
process.exit(1); // 接続エラーの場合はプロセスを終了
});
app.get("/", (req, res) => {
res.send("Server is running and database connection is active.");
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

17
src/config/env.ts Normal file
View File

@ -0,0 +1,17 @@
import dotenv from "dotenv";
// .env ファイルを読み込む
dotenv.config();
const requiredEnvVars = ["DB_NAME", "DB_USER", "DB_PASS", "DB_HOST"];
requiredEnvVars.forEach((varName) => {
if (!process.env[varName]) {
throw new Error(`Environment variable ${varName} is required but not defined.`);
}
});
export const DB_NAME = process.env.DB_NAME as string;
export const DB_USER = process.env.DB_USER as string;
export const DB_PASS = process.env.DB_PASS as string;
export const DB_HOST = process.env.DB_HOST as string;

10
src/models/index.ts Normal file
View File

@ -0,0 +1,10 @@
import { DB_NAME, DB_USER, DB_PASS, DB_HOST } from "../config/env";
import { Sequelize } from "sequelize";
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, {
host: DB_HOST,
dialect: "mysql",
logging: console.log,
});
export default sequelize;

0
src/routes/admin.ts Normal file
View File

13
tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}

16
wait-for-it.sh Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env bash
# wait-for-it.sh -- Wait for a TCP port to be ready
set -e
host="$1"
shift
port="$1"
shift
until nc -z "$host" "$port"; do
echo "Waiting for $host:$port to be ready..."
sleep 1
done
exec "$@"