Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cloudflare] Test PR to check preview builds #10

Open
wants to merge 2 commits into
base: cloudflare_test
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions _routes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"version": 1,
"include": ["/api/*"],
"exclude": []
}
2 changes: 1 addition & 1 deletion client/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ h1 {
width: auto;
padding: 1em;
margin: 1em;
border: 1px solid red;
border: 5px solid red;
border-radius: 5px;
background-color: lightsalmon;
}
Expand Down
6 changes: 3 additions & 3 deletions db/initdb.sql
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
DROP TABLE IF EXISTS videos CASCADE;
DROP TABLE IF EXISTS videos;

CREATE TABLE videos (
id SERIAL,
id INTEGER PRIMARY KEY,
title TEXT,
url TEXT,
rating INT,
created_at TIMESTAMP DEFAULT NOW()
created_at TIMESTAMP DEFAULT current_timestamp
);

INSERT INTO videos (title,url,rating) VALUES ('Never Gonna Give You Up','https://www.youtube.com/watch?v=dQw4w9WgXcQ',23);
Expand Down
56 changes: 56 additions & 0 deletions functions/api/videos/[video]/[action].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export async function onRequestPost(ctx) {
try {
if (ctx.params.action !== "up" && ctx.params.action !== "down") {
return new Response(
JSON.stringify({ success: false, message: "Invalid action!" }),
{ status: 422 }
);
}

const { results } = await ctx.env.db
.prepare("SELECT * FROM videos WHERE id = ?")
.bind(ctx.params.video)
.all();
if (results.length !== 1) {
return new Response(
JSON.stringify({ success: false, message: "Could not find video!" }),
{ status: 404 }
);
}

const operator = ctx.params.action == "up" ? "+" : "-";

const update = await ctx.env.db
.prepare(
`UPDATE videos SET rating = rating ${operator} 1 WHERE id = ? RETURNING *`
)
.bind(ctx.params.video)
.all();
const updateResult = update.results;

if (updateResult.length !== 1) {
return new Response(
JSON.stringify({
success: false,
message: "Error while updating rating",
}),
{ status: 500 }
);
}

return new Response(
JSON.stringify({ success: true, data: updateResult[0] }),
{ status: 200 }
);
} catch (error) {
return new Response(
JSON.stringify({
success: false,
message: "Could not update video!",
error: error.message,
stack: error.stack,
}),
{ status: 500 }
);
}
}
58 changes: 58 additions & 0 deletions functions/api/videos/[video]/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
export async function onRequestGet(ctx) {
try {
const { results } = await ctx.env.db
.prepare("SELECT * FROM videos WHERE id = ?")
.bind(ctx.params.video)
.all();
if (results.length !== 1) {
return new Response(
JSON.stringify({ success: false, message: "Could not find video" }),
{ status: 404 }
);
}

return new Response(JSON.stringify({ success: true, data: results[0] }), {
status: 200,
});
} catch (error) {
return new Response(
JSON.stringify({
success: false,
message: "Could not obtain video!",
error: error.message,
stack: error.stack,
}),
{ status: 500 }
);
}
}

export async function onRequestDelete(ctx) {
try {
const { meta } = await ctx.env.db
.prepare("DELETE FROM videos WHERE id = ?")
.bind(ctx.params.video)
.run();
if (meta.rows_written !== 1) {
return new Response(
JSON.stringify({ success: false, message: "Could not find video" }),
{ status: 404 }
);
}

return new Response(
JSON.stringify({ success: true, message: "Video deleted" }),
{ status: 200 }
);
} catch (error) {
return new Response(
JSON.stringify({
success: false,
message: "Could not obtain video!",
error: error.message,
stack: error.stack,
}),
{ status: 500 }
);
}
}
111 changes: 111 additions & 0 deletions functions/api/videos/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// source: https://stackoverflow.com/questions/3452546/how-do-i-get-the-youtube-video-id-from-a-url
function youtubeLinkParser(url) {
let regExp =
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
let match = url.match(regExp);
return match && match[7].length == 11 ? match[7] : false;
}

export async function onRequestGet(ctx) {
try {
const query = new URLSearchParams(ctx.url);
let orderString = "ORDER BY id ASC";
switch (query.get("order")) {
case "rating_asc":
orderString = "ORDER BY rating ASC";
break;
case "rating_desc":
orderString = "ORDER BY rating DESC";
break;
case "random":
orderString = "ORDER BY random()";
break;
}

const { results } = await ctx.env.db
.prepare("SELECT * FROM videos " + orderString)
.all();
return new Response(
JSON.stringify({
success: true,
total: results.length,
data: results,
}),
{ status: 200 }
);
} catch (error) {
return new Response(
JSON.stringify({
success: false,
message: "Could not finish action!",
error: error.message,
stack: error.stack,
}),
{ status: 500 }
);
}
}

export async function onRequestPost(ctx) {
try {
const body = await ctx.request.json();
if (!body.url || !body.title || !youtubeLinkParser(body.url)) {
return new Response(
JSON.stringify({
success: false,
message: "Missing or invalid input!",
}),
{ status: 422 }
);
}

const insert = await ctx.env.db
.prepare(
"INSERT INTO videos (title,url,rating) VALUES (?,?,?) RETURNING id"
)
.bind(body.title, body.url, 0)
.all();
const insertResult = insert.results;

if (insertResult.length !== 1) {
return new Response(
JSON.stringify({
success: false,
message:
"Server error during video creation, please reload the page!",
}),
{ status: 500 }
);
}

const id = insertResult[0].id;
const { results } = await ctx.env.db
.prepare("SELECT * FROM videos WHERE id = ?")
.bind(id)
.all();
if (results.length !== 1) {
return new Response(
JSON.stringify({
success: false,
message:
"Server error during video creation, please reload the page!",
}),
{ status: 500 }
);
}

return new Response(JSON.stringify({ success: true, data: results[0] }), {
status: 201,
});
} catch (error) {
return new Response(
JSON.stringify({
success: false,
message: "Could not finish action!",
error: error.message,
stack: error.stack,
}),
{ status: 500 }
);
}
}
20 changes: 6 additions & 14 deletions server/db.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import "dotenv/config";

import pkg from "pg";

const { Pool } = pkg;
import { Pool } from "pg";

// make sure we run automated tests against a different database to production
const databaseUrl =
process.env.NODE_ENV == "test"
? process.env.TEST_DATABASE_URL
: process.env.DATABASE_URL;

let pool =
const pool =
databaseUrl &&
new Pool({
connectionString: databaseUrl,
connectionTimeoutMillis: 5000,
ssl: databaseUrl.includes("localhost")
? false
: { rejectUnauthorized: false },
ssl:
databaseUrl.includes("localhost") || databaseUrl.includes("flycast")
? false
: { rejectUnauthorized: false },
});

export const connectDb = async () => {
Expand All @@ -41,13 +40,6 @@ export const disconnectDb = () => {
return;
}
pool.end();
pool = new Pool({
connectionString: databaseUrl,
connectionTimeoutMillis: 5000,
ssl: databaseUrl.includes("localhost")
? false
: { rejectUnauthorized: false },
});
};

export default {
Expand Down
Loading
Loading