forked from zoro-onepiece/Blog-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
172 lines (152 loc) · 5.23 KB
/
Copy pathindex.js
File metadata and controls
172 lines (152 loc) · 5.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";
import { config } from "dotenv";
config();
// console.log("Loaded env:", process.env);
import { marked } from "marked";
import { v4 as uuidv4 } from "uuid";
import methodOverride from "method-override"; // Import method-override
const app = express();
const port = 3006;
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride("_method"));
const postImages = ["/images/girl_read.png", "/images/boy_read.png"];
let posts = [
{
id: uuidv4(),
title: "Featured post",
content: "This is a wider card...",
date: "Nov 12",
},
{
id: uuidv4(),
title: "Post title",
content: "This is another wider card...",
date: "Nov 11",
},
];
app.get("/", (req, res) => {
res.render("index.ejs", { posts: posts });
});
app.get("/new", (req, res) => {
res.render("new.ejs", (err, html) => {
if (err) {
console.error("Error rendering EJS:", err);
return res.status(500).send("Error rendering page");
}
res.send(html);
});
});
app.post("/posts", (req, res) => {
const { title, content } = req.body;
// Add new post to beginning of array
posts.unshift({
id: uuidv4(),
title,
content,
date: new Date().toLocaleDateString("en-US", {
month: "short",
day: "numeric",
}),
image: postImages[Math.floor(Math.random() * postImages.length)],
});
// Redirect to home page to see all posts
res.redirect("/");
});
app.get("/post/:id", (req, res) => {
const postId = req.params.id;
const post = posts.find((p) => p.id === postId);
if (!post) {
return res.status(404).send("Post not found");
}
res.render("show.ejs", { post: post });
});
app.get("/edit/:id", (req, res) => {
const postId = req.params.id;
const post = posts.find((p) => p.id === postId);
if (!post) {
return res.status(404).send("Post not found");
}
res.render("edit.ejs", { post: post }); // Render the edit.ejs template
});
// PUT route to handle updating a post
app.put("/posts/:id", (req, res) => {
const postId = req.params.id;
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).send("Title and content are required for update.");
}
const postIndex = posts.findIndex((p) => p.id === postId);
if (postIndex === -1) {
return res.status(404).send("Post not found.");
}
// Update the existing post
posts[postIndex].title = title;
posts[postIndex].content = content;
// Date and image usually not updated via edit form, but you could add inputs for them
posts[postIndex].date = new Date().toLocaleDateString("en-US", {
month: "short",
day: "numeric",
}); // Update date to today
res.redirect(`/post/${postId}`); // Redirect to the updated post's page
});
// DELETE route to handle deleting a post
app.delete("/posts/:id", (req, res) => {
const postId = req.params.id;
const initialLength = posts.length;
posts = posts.filter((p) => p.id !== postId); // Filter out the post to be deleted
if (posts.length === initialLength) {
// If length hasn't changed, post wasn't found
return res.status(404).send("Post not found for deletion.");
}
res.redirect("/"); // Redirect to the home page after deletion
});
// Chat endpoint using Axios
app.post("/api/chat", async (req, res) => {
try {
const { message } = req.body;
const response = await axios.post(
"https://openrouter.ai/api/v1/chat/completions",
{
model: "deepseek/deepseek-chat", // Specify DeepSeek model via OpenRouter
messages: [
{
role: "system",
content: `You are Dev Door AI, a helpful assistant for the Dev Door blogging website. The website has the following functionalities:
- **Home**: Displays a list of blog posts with titles, dates, and content snippets.
- **About Us**: Provides information about Dev Door, a passionate blogging platform for technology and beyond.
- **Posts**: A section to view all blog posts.
- **New Post**: Allows users to create a new blog post by clicking '+ New Post'.
- **View Post**: Shows detailed content of a specific post when clicking 'Continue reading'.
- **Edit Post**: Enables users to edit an existing post.
- **Delete Post**: Allows users to delete a post.
Respond in proper Markdown format, using double newlines (\\n\\n) for paragraphs and single newlines (\\n) for line breaks within paragraphs. Avoid literal \\n in the output.`,
},
{ role: "user", content: message },
],
},
{
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"HTTP-Referer": "http://localhost:3006", // Required by OpenRouter
"X-Title": "Dev Door Blog", // Optional app name
"Content-Type": "application/json",
},
}
);
const reply = response.data.choices[0].message.content;
res.json(reply);
} catch (error) {
console.error("OpenRouter Error:", error.response?.data || error.message);
res.status(500).json({
error: "Failed to get response",
details: error.response?.data?.error || error.message,
});
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});