Created
October 19, 2024 06:39
-
-
Save kuc-arc-f/5fa6b9ca0ad28b098a8999513083f3e9 to your computer and use it in GitHub Desktop.
Api_chatgpt_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_db_user', | |
host: 'localhost', // データベースホスト(例: localhost) | |
database: 'your_db_name', | |
password: 'your_db_password', | |
port: 5432, // PostgreSQLのデフォルトポート | |
}); | |
// TODOを追加する関数 | |
interface Todo { | |
title: string; | |
content: string; | |
userId: number; | |
completed: number; | |
createdAt: Date; | |
updatedAt: Date; | |
} | |
const addTodo = async (todo: Todo) => { | |
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) | |
RETURNING id; | |
`; | |
const values = [ | |
todo.title, | |
todo.content, | |
todo.userId, | |
todo.completed, | |
todo.createdAt, | |
todo.updatedAt, | |
]; | |
const result = await client.query(query, values); | |
const insertedId = result.rows[0].id; | |
console.log(`TODO added with ID: ${insertedId}`); | |
return insertedId; | |
} catch (error) { | |
console.error('Error adding TODO:', error); | |
} finally { | |
client.release(); | |
} | |
}; | |
// サンプルTODOの追加 | |
const newTodo: Todo = { | |
title: 'Learn TypeScript', | |
content: 'Study the basics of TypeScript and work on projects.', | |
userId: 1, | |
completed: 0, // 0 = 未完了, 1 = 完了 | |
createdAt: new Date(), | |
updatedAt: new Date(), | |
}; | |
addTodo(newTodo) | |
.then((id) => { | |
console.log('New TODO added with ID:', id); | |
}) | |
.catch((error) => { | |
console.error('Failed to add TODO:', error); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment