some more commits

This commit is contained in:
Jonas_Jones 2023-12-08 18:35:05 +01:00
parent dbf32c37f8
commit 4c42b36460
6 changed files with 221 additions and 64 deletions

29
src/v1/builtInRequests.js Normal file
View file

@ -0,0 +1,29 @@
import { internalServerError } from '../stdErrorResponses.js';
import { version } from '../../package.json';
export const builtinRequests = ["ping", "version", "help"];
export function isBuiltinRequest(request) {
return builtinRequests.includes(request);
}
export function returnVersion() {
return new Response(JSON.stringify([version]), {
headers: {
"Content-Type": "application/json"
}
});
}
export function handleBuiltinRequest(request) {
switch (request) {
case "ping":
return new Response("pong");
case "version":
return returnVersion();
case "help":
return new Response("Please refer to the wiki at https://wiki.jonasjones.dev/Api/");
default:
return internalServerError();
}
}

40
src/v1/lastfm/Requests.js Normal file
View file

@ -0,0 +1,40 @@
const lastfmRequests = ['gettrackinfo', 'getrecent']
export function isLastfmRequest(pathname) {
return pathname.startsWith("lastfm/")
}
export function handleLastfmRequest(pathname) {
requestUrl = new URL(pathname, "https://api.jonasjones.dev/v1/" + pathname)
requestType = pathname.replace("lastfm/", "").split("?")[0];
switch (requestType) {
case "gettrackinfo":
return getTrackInfoRequestHandler(requestUrl);
case "getrecent":
return getRecentRequestHandler(requestUrl);
default:
return notFoundError();
}
}
function getRecentRequestHandler(requestUrl) {
const urlParams = new URLSearchParams(requestUrl.search);
const offset = urlParams.get("offset");
const limit = urlParams.get("limit");
return new Response(JSON.stringify([offset, limit]), {
headers: {
"Content-Type": "application/json"
}
});
}
function getTrackInfoRequestHandler(requestUrl) {
const urlParams = new URLSearchParams(requestUrl.search);
const track = urlParams.get("track");
const artist = urlParams.get("artist");
return new Response(JSON.stringify([track, artist]), {
headers: {
"Content-Type": "application/json"
}
});
}

View file

@ -0,0 +1,18 @@
import { isBuiltinRequest, handleBuiltinRequest } from './builtInRequests.js';
import { methodNotAllowedError, notFoundError } from '../stdErrorResponses.js';
import { handleLastfmRequest, isLastfmRequest } from './lastfm/Requests.js';
export async function handleV1Requests(pathname, request) {
if (request.method !== "GET") {
return methodNotAllowedError();
} else {
const requestPath = pathname.replace("/v1/", "");
if (isBuiltinRequest(requestPath)) {
return handleBuiltinRequest(requestPath);
} else if (isLastfmRequest(requestPath)) {
return handleLastfmRequest(requestPath);
} else {
return notFoundError();
}
}
}