Add support for setting a ttl when sending JSON through the API (#31)

This commit is contained in:
Eric Allam
2022-04-29 16:46:46 +01:00
parent b5b1993471
commit 31e3a325ec
2 changed files with 24 additions and 5 deletions
+11 -2
View File
@@ -15,6 +15,11 @@ export type UrlJsonDocument = BaseJsonDocument & {
url: string;
};
export type CreateJsonOptions = {
ttl?: number;
metadata?: any;
};
export type JSONDocument = RawJsonDocument | UrlJsonDocument;
export async function createFromUrlOrRawJson(
@@ -49,12 +54,16 @@ export async function createFromUrl(
export async function createFromRawJson(
filename: string,
contents: string
contents: string,
options?: CreateJsonOptions
): Promise<JSONDocument> {
const docId = createId();
const doc = { id: docId, type: <const>"raw", contents, title: filename };
await DOCUMENTS.put(docId, JSON.stringify(doc));
await DOCUMENTS.put(docId, JSON.stringify(doc), {
expirationTtl: options?.ttl ?? undefined,
metadata: options?.metadata ?? undefined,
});
return doc;
}
+13 -3
View File
@@ -1,12 +1,12 @@
import { ActionFunction, json } from "remix";
import invariant from "tiny-invariant";
import { sendEvent } from "~/graphJSON.server";
import { createFromRawJson } from "~/jsonDoc.server";
import { createFromRawJson, CreateJsonOptions } from "~/jsonDoc.server";
export const action: ActionFunction = async ({ request, context }) => {
const url = new URL(request.url);
const { title, content } = await request.json();
const { title, content, ttl } = await request.json();
if (!title || !content) {
return json({ message: "Missing title or content" }, 400);
@@ -17,7 +17,17 @@ export const action: ActionFunction = async ({ request, context }) => {
const source = url.searchParams.get("utm_source");
const doc = await createFromRawJson(title, JSON.stringify(content));
const options: CreateJsonOptions = {};
if (typeof ttl === "number") {
if (ttl < 60) {
return json({ message: "ttl must be at least 60 seconds" }, 400);
}
options.ttl = ttl;
}
const doc = await createFromRawJson(title, JSON.stringify(content), options);
url.pathname = `/j/${doc.id}`;
url.searchParams.delete("utm_source");