Created
October 19, 2024 06:42
-
-
Save kuc-arc-f/a7d202d1cc237da4ecb9021b86dfe9d3 to your computer and use it in GitHub Desktop.
Api_gemini_addtodo_1018
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from 'pg'; | |
interface Todo { | |
id?: string; | |
title: string; | |
content: string; | |
userId: number; | |
completed: number; | |
createdAt?: Date; | |
updatedAt?: Date; | |
} | |
const pool = new Client({ | |
// PostgreSQL 接続設定 | |
user: 'your_user', | |
host: 'your_host', | |
database: 'your_database', | |
password: 'your_password', | |
port: 5432, // 必要に応じて変更 | |
}); | |
// データベース接続 | |
pool.connect(); | |
/** | |
* TODO をデータベースに追加します。 | |
* @param todo 追加する TODO データ | |
* @returns 追加された TODO データ | |
*/ | |
async function createTodo(todo: Todo): Promise<Todo> { | |
try { | |
const { title, content, userId, completed } = todo; | |
const result = await pool.query( | |
'INSERT INTO todos (title, content, user_id, completed, created_at, updated_at) VALUES ($1, $2, $3, $4, NOW(), NOW()) RETURNING *', | |
[title, content, userId, completed] | |
); | |
return result.rows[0]; | |
} catch (error) { | |
console.error('TODOの作成エラー:', error); | |
throw error; | |
} | |
} | |
// 使用例 | |
const newTodo: Todo = { | |
title: 'サンプルタスク', | |
content: 'サンプルタスクの詳細', | |
userId: 1, | |
completed: 0, // 0: 未完了, 1: 完了 | |
}; | |
createTodo(newTodo) | |
.then((createdTodo) => { | |
console.log('TODO が作成されました:', createdTodo); | |
}) | |
.catch((error) => { | |
console.error('TODO の作成に失敗しました:', error); | |
}) | |
.finally(() => { | |
// 接続の解放 | |
pool.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment