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 example with-drizzle #1501

Merged
merged 5 commits into from
May 28, 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
30 changes: 30 additions & 0 deletions examples/with-drizzle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# SolidStart

Everything you need to build a Solid project, powered by [`solid-start`](https://start.solidjs.com);

## Creating a project

```bash
# create a new project in the current directory
npm init solid@latest

# create a new project in my-app
npm init solid@latest my-app
```

## Developing

Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:

```bash
npm run dev

# or start the server and open the app in a new browser tab
npm run dev
```

## Building

Solid apps are built with _adapters_, which optimise your project for deployment to different environments.

By default, `npm run build` will generate a Node app that you can run with `npm start`. To use a different adapter, add it to the `devDependencies` in `package.json` and specify in your `app.config.js`.
7 changes: 7 additions & 0 deletions examples/with-drizzle/app.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "@solidjs/start/config";

export default defineConfig({
vite: {
ssr: { external: ["drizzle-orm"] },
},
});
10 changes: 10 additions & 0 deletions examples/with-drizzle/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// import { type Config } from "drizzle-kit";

export default {
schema: "./drizzle/schema.ts",
out: "./drizzle/migrations/",
driver: "better-sqlite",
dbCredentials: {
url: './drizzle/db.sqlite',
},
};
Binary file added examples/with-drizzle/drizzle/db.sqlite
Binary file not shown.
7 changes: 7 additions & 0 deletions examples/with-drizzle/drizzle/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { integer, text, sqliteTable } from "drizzle-orm/sqlite-core";

export const Users = sqliteTable("users", {
id: integer("id").primaryKey().unique().notNull(),
username: text("username").notNull().default(""),
password: text("password").notNull().default(""),
});
12 changes: 12 additions & 0 deletions examples/with-drizzle/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// <reference types="vinxi/types/client" />

interface ImportMetaEnv {
DB_URL: string;
DB_MIGRATIONS_URL: string;
SITE_NAME: string;
SESSION_SECRET: string;
}

interface ImportMeta {
readonly env: ImportMetaEnv
}
25 changes: 25 additions & 0 deletions examples/with-drizzle/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "example-with-drizzle",
"type": "module",
"scripts": {
"dev": "vinxi dev",
"build": "vinxi build",
"start": "vinxi start"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.10",
"@types/node": "^20.12.12",
"drizzle-kit": "^0.21.4"
},
"dependencies": {
"@solidjs/router": "^0.13.3",
"@solidjs/start": "^1.0.0",
"better-sqlite3": "^10.0.0",
"drizzle-orm": "^0.30.10",
"solid-js": "^1.8.17",
"vinxi": "0.3.11"
},
"engines": {
"node": ">=20"
}
}
Binary file added examples/with-drizzle/public/favicon.ico
Binary file not shown.
6 changes: 6 additions & 0 deletions examples/with-drizzle/src/api/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { drizzle, BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
import Database from "better-sqlite3";

const sqlite = new Database('./drizzle/db.sqlite');

export const db: BetterSQLite3Database = drizzle(sqlite);
6 changes: 6 additions & 0 deletions examples/with-drizzle/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { action, cache } from "@solidjs/router";
import { getUser as gU, logout as l, loginOrRegister as lOR } from "./server";

export const getUser = cache(gU, "user");
export const loginOrRegister = action(lOR, "loginOrRegister");
export const logout = action(l, "logout");
84 changes: 84 additions & 0 deletions examples/with-drizzle/src/api/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"use server";
import { redirect } from "@solidjs/router";
import { useSession } from "vinxi/http";
import { eq } from "drizzle-orm";
import { db } from "./db";
import { Users } from "../../drizzle/schema";

function validateUsername(username: unknown) {
if (typeof username !== "string" || username.length < 3) {
return `Usernames must be at least 3 characters long`;
}
}

function validatePassword(password: unknown) {
if (typeof password !== "string" || password.length < 6) {
return `Passwords must be at least 6 characters long`;
}
}

async function login(username: string, password: string) {
const user = db.select().from(Users).where(eq(Users.username, username)).get();
if (!user || password !== user.password) throw new Error("Invalid login");
return user;
}

async function register(username: string, password: string) {
const existingUser = db
.select()
.from(Users)
.where(eq(Users.username, username))
.get();
if (existingUser) throw new Error("User already exists");
return db
.insert(Users)
.values({ username, password })
.returning()
.get();
}

function getSession() {
return useSession({
password:
process.env.SESSION_SECRET ?? "areallylongsecretthatyoushouldreplace",
});
}

export async function loginOrRegister(formData: FormData) {
const username = String(formData.get("username"));
const password = String(formData.get("password"));
const loginType = String(formData.get("loginType"));
let error = validateUsername(username) || validatePassword(password);
if (error) return new Error(error);

try {
const user = await (loginType !== "login"
? register(username, password)
: login(username, password));
const session = await getSession();
await session.update(d => (d.userId = user!.id));
} catch (err) {
return err as Error;
}
throw redirect("/");
}

export async function logout() {
const session = await getSession();
await session.update((d) => (d.userId = undefined));
throw redirect("/login");
}

export async function getUser() {
const session = await getSession();
const userId = session.data.userId;
if (userId === undefined) throw redirect("/login");

try {
const user = db.select().from(Users).where(eq(Users.id, userId)).get();
if (!user) throw redirect("/login");
return { id: user.id, username: user.username };
} catch {
throw logout();
}
}
39 changes: 39 additions & 0 deletions examples/with-drizzle/src/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
body {
font-family: Gordita, Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

a {
margin-right: 1rem;
}

main {
text-align: center;
padding: 1em;
margin: 0 auto;
}

h1 {
color: #335d92;
text-transform: uppercase;
font-size: 4rem;
font-weight: 100;
line-height: 1.1;
margin: 4rem auto;
max-width: 14rem;
}

p {
max-width: 14rem;
margin: 2rem auto;
line-height: 1.35;
}

@media (min-width: 480px) {
h1 {
max-width: none;
}

p {
max-width: none;
}
}
21 changes: 21 additions & 0 deletions examples/with-drizzle/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// @refresh reload
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense } from "solid-js";
import "./app.css";

export default function App() {
return (
<Router
root={props => (
<>
<a href="/">Index</a>
<a href="/about">About</a>
<Suspense>{props.children}</Suspense>
</>
)}
>
<FileRoutes />
</Router>
);
}
4 changes: 4 additions & 0 deletions examples/with-drizzle/src/entry-client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// @refresh reload
import { mount, StartClient } from "@solidjs/start/client";

mount(() => <StartClient />, document.getElementById("app")!);
21 changes: 21 additions & 0 deletions examples/with-drizzle/src/entry-server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// @refresh reload
import { StartServer, createHandler } from "@solidjs/start/server";

export default createHandler(() => (
<StartServer
document={({ assets, children, scripts }) => (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
{assets}
</head>
<body>
<div id="app">{children}</div>
{scripts}
</body>
</html>
)}
/>
));
1 change: 1 addition & 0 deletions examples/with-drizzle/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="@solidjs/start/env" />
7 changes: 7 additions & 0 deletions examples/with-drizzle/src/routes/[...404].tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function NotFound() {
return (
<main class="w-full p-4 space-y-2">
<h1 class="font-bold text-xl">Page Not Found</h1>
</main>
);
}
21 changes: 21 additions & 0 deletions examples/with-drizzle/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createAsync, type RouteDefinition } from "@solidjs/router";
import { getUser, logout } from "~/api";

export const route = {
load: () => getUser()
} satisfies RouteDefinition;

export default function Home() {
const user = createAsync(async () => getUser(), { deferStream: true });
return (
<main class="w-full p-4 space-y-2">
<h2 class="font-bold text-3xl">Hello {user()?.username}</h2>
<h3 class="font-bold text-xl">Message board</h3>
<form action={logout} method="post">
<button name="logout" type="submit">
Logout
</button>
</form>
</main>
);
}
42 changes: 42 additions & 0 deletions examples/with-drizzle/src/routes/login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
useSubmission,
type RouteSectionProps
} from "@solidjs/router";
import { Show } from "solid-js";
import { loginOrRegister } from "~/api";

export default function Login(props: RouteSectionProps) {
const loggingIn = useSubmission(loginOrRegister);

return (
<main>
<h1>Login</h1>
<form action={loginOrRegister} method="post">
<input type="hidden" name="redirectTo" value={props.params.redirectTo ?? "/"} />
<fieldset>
<legend>Login or Register?</legend>
<label>
<input type="radio" name="loginType" value="login" checked={true} /> Login
</label>
<label>
<input type="radio" name="loginType" value="register" /> Register
</label>
</fieldset>
<div>
<label for="username-input">Username</label>
<input name="username" placeholder="kody" autocomplete="username" />
</div>
<div>
<label for="password-input">Password</label>
<input name="password" type="password" placeholder="twixrox" autocomplete="current-password" />
</div>
<button type="submit">Login</button>
<Show when={loggingIn.result}>
<p style={{color: "red"}} role="alert" id="error-message">
{loggingIn.result!.message}
</p>
</Show>
</form>
</main>
);
}
20 changes: 20 additions & 0 deletions examples/with-drizzle/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"jsx": "preserve",
"jsxImportSource": "solid-js",
"allowJs": true,
"strict": true,
"noEmit": true,
"types": ["vinxi/types/client", "node"],
"isolatedModules": true,
"paths": {
"~/*": ["./src/*"],
"@/*": ["./drizzle/*"]
}
}
}
Loading