Created
October 19, 2024 06:41
-
-
Save kuc-arc-f/d836e0540a09be5e4d4ff52affa7bc63 to your computer and use it in GitHub Desktop.
Api_claude_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 { Pool } from 'pg'; | |
// PostgreSQLの接続設定 | |
const pool = new Pool({ | |
user: 'your_username', | |
host: 'localhost', | |
database: 'your_database', | |
password: 'your_password', | |
port: 5432, | |
}); | |
interface Todo { | |
title: string; | |
content: string; | |
userId: number; | |
completed: number; | |
} | |
async function addTodoToDatabase(todo: Todo): Promise<void> { | |
const client = await pool.connect(); | |
try { | |
const query = ` | |
INSERT INTO todos (title, content, user_id, completed, created_at, updated_at) | |
VALUES ($1, $2, $3, $4, $5, $6) | |
`; | |
const now = new Date(); | |
const values = [todo.title, todo.content, todo.userId, todo.completed, now, now]; | |
await client.query(query, values); | |
console.log('TODO item added successfully'); | |
} catch (error) { | |
console.error('Error adding TODO item:', error); | |
throw error; | |
} finally { | |
client.release(); | |
} | |
} | |
// 使用例 | |
const newTodo: Todo = { | |
title: 'テストTODO', | |
content: 'これはテスト用のTODOアイテムです。', | |
userId: 1, | |
completed: 0 | |
}; | |
addTodoToDatabase(newTodo) | |
.then(() => console.log('TODO added successfully')) | |
.catch(error => console.error('Error:', error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment