Skip to content

Commit

Permalink
Change indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
benvinegar committed Dec 24, 2023
1 parent ecc2330 commit 31881c4
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 244 deletions.
132 changes: 66 additions & 66 deletions app/analytics/index.ts
Original file line number Diff line number Diff line change
@@ -1,93 +1,93 @@
interface AnalyticsQueryResult {
meta: string,
data: [
{
[key: string]: any
}
],
rows: number,
rows_before_limit_at_least: number
meta: string,
data: [
{
[key: string]: any
}
],
rows: number,
rows_before_limit_at_least: number
}

export class AnalyticsEngineAPI {
cfApiToken: string;
cfAccountId: string;
defaultHeaders: {
"content-type": string;
"X-Source": string;
"Authorization": string;
};
defaultUrl: string;
cfApiToken: string;
cfAccountId: string;
defaultHeaders: {
"content-type": string;
"X-Source": string;
"Authorization": string;
};
defaultUrl: string;

constructor(cfAccountId: string, cfApiToken: string) {
this.cfAccountId = cfAccountId;
this.cfApiToken = cfApiToken;
constructor(cfAccountId: string, cfApiToken: string) {
this.cfAccountId = cfAccountId;
this.cfApiToken = cfApiToken;

this.defaultUrl = `https://api.cloudflare.com/client/v4/accounts/${this.cfAccountId}/analytics_engine/sql`;
this.defaultHeaders = {
"content-type": "application/json;charset=UTF-8",
"X-Source": "Cloudflare-Workers",
"Authorization": `Bearer ${this.cfApiToken}`
this.defaultUrl = `https://api.cloudflare.com/client/v4/accounts/${this.cfAccountId}/analytics_engine/sql`;
this.defaultHeaders = {
"content-type": "application/json;charset=UTF-8",
"X-Source": "Cloudflare-Workers",
"Authorization": `Bearer ${this.cfApiToken}`
}
}
}

async getCount(sinceDays: number): Promise<number> {
// defaults to 1 day if not specified
const interval = sinceDays || 1;
async getCount(sinceDays: number): Promise<number> {
// defaults to 1 day if not specified
const interval = sinceDays || 1;

const query = `
const query = `
SELECT SUM(_sample_interval) as count
FROM metricsDataset
WHERE timestamp > NOW() - INTERVAL '${interval}' DAY`;

const returnPromise = new Promise<number>((resolve, reject) => (async () => {
const response = await fetch(this.defaultUrl, {
method: 'POST',
body: query,
headers: this.defaultHeaders,
});
const returnPromise = new Promise<number>((resolve, reject) => (async () => {
const response = await fetch(this.defaultUrl, {
method: 'POST',
body: query,
headers: this.defaultHeaders,
});

if (!response.ok) {
reject(response.statusText);
}
if (!response.ok) {
reject(response.statusText);
}

const responseData = await response.json() as AnalyticsQueryResult;
resolve(responseData.data[0]['count']);
})());
return returnPromise;
}
const responseData = await response.json() as AnalyticsQueryResult;
resolve(responseData.data[0]['count']);
})());
return returnPromise;
}

async getCountByReferer(sinceDays: number): Promise<any> {
// defaults to 1 day if not specified
const interval = sinceDays || 1;
async getCountByReferer(sinceDays: number): Promise<any> {
// defaults to 1 day if not specified
const interval = sinceDays || 1;

const query = `
const query = `
SELECT SUM(_sample_interval) as count, blob2 as referer
FROM metricsDataset
WHERE timestamp > NOW() - INTERVAL '${interval}' DAY
GROUP BY referer
ORDER BY count DESC
`;

const returnPromise = new Promise<any>((resolve, reject) => (async () => {
const response = await fetch(this.defaultUrl, {
method: 'POST',
body: query,
headers: this.defaultHeaders,
});
const returnPromise = new Promise<any>((resolve, reject) => (async () => {
const response = await fetch(this.defaultUrl, {
method: 'POST',
body: query,
headers: this.defaultHeaders,
});

if (!response.ok) {
reject(response.statusText);
}
if (!response.ok) {
reject(response.statusText);
}

const responseData = await response.json() as AnalyticsQueryResult;
var result = responseData.data.reduce((acc, cur) => {
acc.push([cur['referer'], cur['count']]);
return acc;
}, []);
console.log(result);;
resolve(result);
})());
return returnPromise;
}
const responseData = await response.json() as AnalyticsQueryResult;
var result = responseData.data.reduce((acc, cur) => {
acc.push([cur['referer'], cur['count']]);
return acc;
}, []);
console.log(result);;
resolve(result);
})());
return returnPromise;
}
}
12 changes: 6 additions & 6 deletions app/entry.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});
54 changes: 27 additions & 27 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,34 @@ import isbot from "isbot";
import { renderToReadableStream } from "react-dom/server";

export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
const body = await renderToReadableStream(
<RemixServer context={remixContext} url={request.url} />,
{
signal: request.signal,
onError(error: unknown) {
// Log streaming rendering errors from inside the shell
console.error(error);
responseStatusCode = 500;
},
}
);
const body = await renderToReadableStream(
<RemixServer context={remixContext} url={request.url} />,
{
signal: request.signal,
onError(error: unknown) {
// Log streaming rendering errors from inside the shell
console.error(error);
responseStatusCode = 500;
},
}
);

if (isbot(request.headers.get("user-agent"))) {
await body.allReady;
}
if (isbot(request.headers.get("user-agent"))) {
await body.allReady;
}

responseHeaders.set("Content-Type", "text/html");
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
});
responseHeaders.set("Content-Type", "text/html");
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
});
}
46 changes: 23 additions & 23 deletions app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import type { LinksFunction } from "@remix-run/cloudflare";
import { cssBundleHref } from "@remix-run/css-bundle";
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "@remix-run/react";

export const links: LinksFunction = () => [
...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []),
...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []),
];

export default function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
76 changes: 38 additions & 38 deletions app/routes/_index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,53 @@ import { useLoaderData } from "@remix-run/react";
import { AnalyticsEngineAPI } from "../analytics";

export const meta: MetaFunction = () => {
return [
{ title: "New Remix App" },
{ name: "description", content: "Welcome to Remix!" },
];
return [
{ title: "New Remix App" },
{ name: "description", content: "Welcome to Remix!" },
];
};

declare module "@remix-run/server-runtime" {
export interface AppLoadContext {
env: {
CF_BEARER_TOKEN: string,
CF_ACCOUNT_ID: string
};
}
export interface AppLoadContext {
env: {
CF_BEARER_TOKEN: string,
CF_ACCOUNT_ID: string
};
}
}

export const loader = async ({ context }: LoaderFunctionArgs) => {
const analyticsEngine = new AnalyticsEngineAPI(context.env.CF_ACCOUNT_ID, context.env.CF_BEARER_TOKEN);
const analyticsEngine = new AnalyticsEngineAPI(context.env.CF_ACCOUNT_ID, context.env.CF_BEARER_TOKEN);

const days = 1;
const count = analyticsEngine.getCount(days);
const countByReferer = analyticsEngine.getCountByReferer(days);
const days = 1;
const count = analyticsEngine.getCount(days);
const countByReferer = analyticsEngine.getCountByReferer(days);

return json({
test: "testing",
count: await count,
countByReferer: await countByReferer
});
return json({
test: "testing",
count: await count,
countByReferer: await countByReferer
});
};

export default function Index() {
const data = useLoaderData<typeof loader>();

return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>Welcome to Tally-ho</h1>

<h2>Hits</h2>
<ul>
<li>Hits (all time): {data.count}</li>
</ul>

<h2>Hits by Referer</h2>
<ul>
{data.countByReferer.map((item: any) => (
<li key={item[0]}>{item[0]}: {item[1]}</li>
))}
</ul>
</div>
);
const data = useLoaderData<typeof loader>();

return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>Welcome to Tally-ho</h1>

<h2>Hits</h2>
<ul>
<li>Hits (all time): {data.count}</li>
</ul>

<h2>Hits by Referer</h2>
<ul>
{data.countByReferer.map((item: any) => (
<li key={item[0]}>{item[0]}: {item[1]}</li>
))}
</ul>
</div>
);
}
Loading

0 comments on commit 31881c4

Please sign in to comment.