mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-04-25 03:49:11 +00:00
feat(api): add get-slug
This commit is contained in:
parent
a85c4d5ddd
commit
c55ce3b828
7 changed files with 100 additions and 38 deletions
|
@ -51,6 +51,7 @@ class KVShim {
|
|||
}
|
||||
|
||||
async get(key, type = 'text') {
|
||||
try {
|
||||
const result = JSON.parse(await this.level.get(key));
|
||||
|
||||
if (!this.validate(result)) {
|
||||
|
@ -58,6 +59,9 @@ class KVShim {
|
|||
}
|
||||
|
||||
return getConversion[type](result.value);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getWithMetadata(key, type) {
|
||||
|
|
|
@ -30,14 +30,7 @@ const context = () =>
|
|||
listeners.push(fn);
|
||||
}
|
||||
},
|
||||
Response: class {
|
||||
constructor(body, opts = {}) {
|
||||
this.body = Buffer.from(body || '');
|
||||
this.headers = opts.headers || {};
|
||||
this.url = opts.url || {};
|
||||
this.status = opts.status || 200;
|
||||
}
|
||||
},
|
||||
Response: fetch.Response,
|
||||
URL: URL,
|
||||
crypto: crypto,
|
||||
setTimeout: setTimeout,
|
||||
|
@ -45,6 +38,7 @@ const context = () =>
|
|||
clearInterval: clearInterval,
|
||||
clearTimeout: clearTimeout,
|
||||
fetch: fetch,
|
||||
console: console,
|
||||
...workerShims,
|
||||
},
|
||||
{
|
||||
|
@ -59,24 +53,37 @@ const server = http.createServer((req, res) => {
|
|||
const event = {
|
||||
respondWith: async (value) => {
|
||||
const timeStart = Date.now();
|
||||
let loggedStatus = 'xxx';
|
||||
try {
|
||||
const response = await value;
|
||||
const timeEnd = Date.now();
|
||||
console.log(
|
||||
`${response.status} [${timeEnd - timeStart}ms] - ${req.method} ${req.url}`
|
||||
if (!response) {
|
||||
throw new Error(
|
||||
`response was invalid, got ${JSON.stringify(response)}`
|
||||
);
|
||||
}
|
||||
res.statusCode = response.status;
|
||||
loggedStatus = String(response.status);
|
||||
Object.entries(response.headers).forEach(([k, v]) => res.setHeader(k, v));
|
||||
res.end(response.body);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.statusCode = 500;
|
||||
loggedStatus = '500';
|
||||
res.end(JSON.stringify({ error: 'internal server error' }));
|
||||
}
|
||||
const timeEnd = Date.now();
|
||||
console.log(
|
||||
`${loggedStatus} [${timeEnd - timeStart}ms] - ${req.method} ${req.url}`
|
||||
);
|
||||
},
|
||||
request: {
|
||||
url: `http://${req.headers.host || 'localhost'}${req.url}`,
|
||||
body: req,
|
||||
headers: Object.entries(req.headers).reduce(
|
||||
(acc, [k, v]) => acc.set(k, v),
|
||||
new Map()
|
||||
),
|
||||
request: new fetch.Request(
|
||||
new URL(`http://${req.headers.host || 'localhost'}${req.url}`),
|
||||
{
|
||||
body: ['GET', 'HEAD'].includes(req.method) ? undefined : req,
|
||||
headers: req.headers,
|
||||
method: req.method,
|
||||
},
|
||||
}
|
||||
),
|
||||
};
|
||||
|
||||
event.request.headers.set('cf-client-ip', req.connection.remoteAddress);
|
||||
|
@ -110,6 +117,7 @@ const reload = () => {
|
|||
context(),
|
||||
{
|
||||
displayErrors: true,
|
||||
filename: 'worker.js',
|
||||
}
|
||||
)
|
||||
);
|
||||
|
@ -124,6 +132,11 @@ const rebuild = () =>
|
|||
console.log('Compilation failed.', err);
|
||||
reject(err);
|
||||
} else {
|
||||
if (stats.hasErrors()) {
|
||||
console.error('Compilation errored:', stats.compilation.errors);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Compilation done.');
|
||||
resolve();
|
||||
}
|
||||
|
|
|
@ -1,9 +1,42 @@
|
|||
import { Guild } from "roleypoly/common/types";
|
||||
import { discordFetch } from "../utils/api-tools";
|
||||
import { GuildSlug } from 'roleypoly/common/types';
|
||||
import { respond } from '../utils/api-tools';
|
||||
import { getGuild } from '../utils/guild';
|
||||
|
||||
export const GetSlug = async (request: Request): Promise<Response> => {
|
||||
const reqURL = new URL(request.url)
|
||||
const serverID = reqURL.pathname.split('/')[2]
|
||||
// return respond({ hello: 'world' });
|
||||
const reqURL = new URL(request.url);
|
||||
const [, , serverID] = reqURL.pathname.split('/');
|
||||
|
||||
const serverPayload = discordFetch<Guild>
|
||||
if (!serverID) {
|
||||
return respond(
|
||||
{
|
||||
error: 'missing server ID',
|
||||
},
|
||||
{
|
||||
status: 400,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const guild = await getGuild(serverID);
|
||||
if (!guild) {
|
||||
return respond(
|
||||
{
|
||||
error: 'guild not found',
|
||||
},
|
||||
{
|
||||
status: 404,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const { id, name, icon } = guild;
|
||||
const guildSlug: GuildSlug = {
|
||||
id,
|
||||
name,
|
||||
icon,
|
||||
permissionLevel: 0,
|
||||
};
|
||||
console.log({ guildSlug });
|
||||
return respond(guildSlug);
|
||||
};
|
||||
|
|
|
@ -34,7 +34,7 @@ export class Router {
|
|||
this.routingTree[lowerMethod][rootPath] = handler;
|
||||
}
|
||||
|
||||
handle(request: Request): Promise<Response> | Response {
|
||||
async handle(request: Request): Promise<Response> | Response {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === '/' || url.pathname === '') {
|
||||
|
|
|
@ -23,7 +23,7 @@ export const resolveFailures = (
|
|||
return handler(request);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return handleWith;
|
||||
return handleWith || respond({ error: 'internal server error' }, { status: 500 });
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -60,7 +60,7 @@ export const discordFetch = async <T>(
|
|||
url: string,
|
||||
auth: string,
|
||||
authType: 'Bearer' | 'Bot' = 'Bearer'
|
||||
): Promise<T> => {
|
||||
): Promise<T | null> => {
|
||||
const response = await fetch('https://discord.com/api/v8' + url, {
|
||||
headers: {
|
||||
authorization: `${authType} ${auth}`,
|
||||
|
@ -69,7 +69,11 @@ export const discordFetch = async <T>(
|
|||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return (await response.json()) as T;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const cacheLayer = <Identity, Data>(
|
||||
|
@ -86,7 +90,6 @@ export const cacheLayer = <Identity, Data>(
|
|||
}
|
||||
|
||||
const fallbackValue = await missHandler(identity);
|
||||
|
||||
if (!fallbackValue) {
|
||||
return null;
|
||||
}
|
||||
|
|
|
@ -26,6 +26,10 @@ export const getGuild = cacheLayer(
|
|||
async (id: string) => {
|
||||
const guildRaw = await discordFetch<APIGuild>(`/guilds/${id}`, botToken, 'Bot');
|
||||
|
||||
if (!guildRaw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filters the raw guild data into data we actually want
|
||||
const guild: Guild = {
|
||||
id: guildRaw.id,
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
const path = require('path');
|
||||
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
|
||||
|
||||
const mode = process.env.NODE_ENV || 'production';
|
||||
|
||||
|
@ -12,7 +13,11 @@ module.exports = {
|
|||
mode,
|
||||
resolve: {
|
||||
extensions: ['.ts', '.tsx', '.js'],
|
||||
plugins: [],
|
||||
plugins: [
|
||||
new TsconfigPathsPlugin({
|
||||
configFile: path.resolve(__dirname, './tsconfig.json'),
|
||||
}),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
|
|
Loading…
Add table
Reference in a new issue