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

add database seeding, fix view snippets page, typescript types loaded for imported snippets #40

Merged
merged 7 commits into from
Oct 8, 2024
Merged
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
27 changes: 23 additions & 4 deletions fake-snippets-api/lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createStore, type StoreApi } from "zustand/vanilla"
import { immer } from "zustand/middleware/immer"
import { hoist, type HoistedStoreApi } from "zustand-hoist"
import { z } from "zod"

import {
databaseSchema,
Expand All @@ -9,24 +10,42 @@ import {
LoginPage,
Account,
type DatabaseSchema,
snippetSchema,
} from "./schema.ts"
import { combine } from "zustand/middleware"
import { seed as seedFn } from "./seed"

export const createDatabase = () => {
return hoist(createStore(initializer))
export const createDatabase = ({ seed }: { seed?: boolean } = {}) => {
const db = hoist(createStore(initializer))
if (seed) {
seedFn(db)
}
return db
}

export type DbClient = ReturnType<typeof createDatabase>

const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addSnippet: (snippet: Omit<Snippet, "snippet_id">) => {
addAccount: (account: Omit<Account, "account_id">) => {
set((state) => {
const newAccountId = `account_${state.idCounter + 1}`
return {
accounts: [...state.accounts, { account_id: newAccountId, ...account }],
idCounter: state.idCounter + 1,
}
})
},
addSnippet: (snippet: Omit<z.input<typeof snippetSchema>, "snippet_id">) => {
let newSnippet
set((state) => {
const newSnippetId = `snippet_${state.idCounter + 1}`
newSnippet = snippetSchema.parse({ ...snippet, snippet_id: newSnippetId })
return {
snippets: [...state.snippets, { snippet_id: newSnippetId, ...snippet }],
snippets: [...state.snippets, newSnippet],
idCounter: state.idCounter + 1,
}
})
return newSnippet
},
getNewestSnippets: (limit: number): Snippet[] => {
const state = get()
Expand Down
2 changes: 2 additions & 0 deletions fake-snippets-api/lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ export const snippetSchema = z.object({
unscoped_name: z.string(),
owner_name: z.string(),
code: z.string(),
dts: z.string().optional(),
created_at: z.string(),
updated_at: z.string(),
snippet_type: z.enum(["board", "package", "model", "footprint"]),
description: z.string().optional(),
version: z.string().default("0.0.1"),
})
export type Snippet = z.infer<typeof snippetSchema>

Expand Down
51 changes: 51 additions & 0 deletions fake-snippets-api/lib/db/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { DbClient } from "./db-client"

export const seed = (db: DbClient) => {
db.addAccount({
github_username: "testuser",
})
db.addAccount({
github_username: "seveibar",
})
db.addSnippet({
name: "My Test Board",
unscoped_name: "my-test-board",
owner_name: "testuser",
code: `
import { A555Timer } from "@tsci/seveibar.a555timer"

export default () => (
<board width="10mm" height="10mm">
<A555Timer />
</board>
)`.trim(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
snippet_type: "board",
description: "A simple board with an A555 Timer component",
})

// Define the @tsci/seveibar.a555timer package
db.addSnippet({
name: "seveibar/a555timer",
unscoped_name: "a555timer",
owner_name: "seveibar",
code: `
export const A555Timer = ({ name }: { name: string }) => (
<chip name={name} footprint="dip8" />
)
`.trim(),
dts: `
declare module "@tsci/seveibar.a555timer" {
export const A555Timer: ({ name }: {
name: string;
}) => any;
}
`.trim(),

created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
snippet_type: "package",
description: "A simple package with an A555 Timer component",
})
}
4 changes: 2 additions & 2 deletions fake-snippets-api/routes/api/snippets/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default withRouteSpec({
if (!unscoped_name) {
unscoped_name = `untitled-${snippet_type}-${ctx.db.idCounter + 1}`
}
const newSnippet: Snippet = {
const newSnippet: z.input<typeof snippetSchema> = {
snippet_id: `snippet_${ctx.db.idCounter + 1}`,
name: `${ctx.auth.github_username}/${unscoped_name}`,
unscoped_name,
Expand All @@ -41,6 +41,6 @@ export default withRouteSpec({

return ctx.json({
ok: true,
snippet: newSnippet,
snippet: newSnippet as any,
})
})
145 changes: 145 additions & 0 deletions fake-snippets-api/routes/api/snippets/download.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { withRouteSpec } from "fake-snippets-api/lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
auth: "none",
queryParams: z.object({
jsdelivr_resolve: z.enum(["true", "false"]).transform((v) => v === "true"),
jsdelivr_path: z.string(),
}),
jsonResponse: z.any(),
})(async (req, ctx) => {
const { jsdelivr_path, jsdelivr_resolve } = req.query

// Parse the file path
const [owner, packageWithVersion, ...rest] = jsdelivr_path.split("/")
const [packageName, version] = packageWithVersion.split("@")
const fileName = rest.join("/")

// Find the snippet
const snippet = ctx.db.snippets.find(
(s) => s.owner_name === owner && s.unscoped_name === packageName,
)

if (!snippet) {
return ctx.error(404, {
error_code: "snippet_not_found",
message: "Snippet not found",
})
}

if (!fileName && !jsdelivr_resolve) {
return new Response(
JSON.stringify({
tags: {
latest: "0.0.1",
},
versions: ["0.0.1"],
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
)
} else if (!fileName && jsdelivr_resolve) {
return new Response(
JSON.stringify({
version: "0.0.1",
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
)
}

// If no fileName is provided, return the directory listing
if (!fileName || fileName === "flat") {
const files = [
{
type: "file",
name: "index.ts",
hash: "placeholder_hash",
time: snippet.updated_at,
size: snippet.code.length,
},
{
type: "file",
name: "index.d.ts",
hash: "placeholder_hash",
time: snippet.updated_at,
size: (snippet.dts || "").length,
},
{
type: "file",
name: "package.json",
hash: "placeholder_hash",
time: snippet.updated_at,
size: JSON.stringify({
name: `@tsci/${owner}.${packageName}`,
version: version || "0.0.1",
main: "index.ts",
types: "index.d.ts",
}).length,
},
]

const response = {
default: "/index.ts",
files:
fileName === "flat"
? files.map((f) => ({
name: `/${f.name}`,
hash: f.hash,
time: f.time,
size: f.size,
}))
: [
{
type: "directory",
name: ".",
files: files,
},
],
}

return new Response(JSON.stringify(response, null, 2), {
status: 200,
headers: { "Content-Type": "application/json" },
})
}

// Handle file downloads
let content: string
switch (fileName) {
case "index.ts":
content = snippet.code
break
case "index.d.ts":
content = snippet.dts || ""
break
case "package.json":
content = JSON.stringify(
{
name: `@tsci/${owner}.${packageName}`,
version: version || "0.0.1",
main: "index.ts",
types: "index.d.ts",
},
null,
2,
)
break
default:
return ctx.error(404, {
error_code: "file_not_found",
message: "Requested file not found",
})
}

return new Response(content, {
status: 200,
headers: { "Content-Type": "text/plain" },
})
})
4 changes: 1 addition & 3 deletions fake-snippets-api/routes/api/snippets/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export default withRouteSpec({
jsonBody: z.any().optional(),
jsonResponse: z.object({
ok: z.boolean(),
snippet: snippetSchema.extend({
snippet_type: z.enum(["board", "package", "model", "footprint"]),
}),
snippet: snippetSchema,
}),
})(async (req, ctx) => {
const { snippet_id, name, owner_name, unscoped_name } = req.commonParams
Expand Down
4 changes: 3 additions & 1 deletion fake-snippets-api/routes/api/snippets/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default withRouteSpec({
code: z.string().optional(),
description: z.string().optional(),
unscoped_name: z.string().optional(),
dts: z.string().optional(),
}),
jsonResponse: z.object({
ok: z.boolean(),
Expand All @@ -18,7 +19,7 @@ export default withRouteSpec({
}),
}),
})(async (req, ctx) => {
const { snippet_id, code, description, unscoped_name } = req.jsonBody
const { snippet_id, code, description, unscoped_name, dts } = req.jsonBody

const snippetIndex = ctx.db.snippets.findIndex(
(s) => s.snippet_id === snippet_id,
Expand Down Expand Up @@ -48,6 +49,7 @@ export default withRouteSpec({
name: unscoped_name
? `${ctx.auth.github_username}/${unscoped_name}`
: snippet.name,
dts: dts ?? snippet.dts,
updated_at: new Date().toISOString(),
}

Expand Down
Loading
Loading