feat: add drizzle
This commit is contained in:
@@ -1,11 +1,15 @@
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { genericOAuth } from "better-auth/plugins";
|
||||
import { expo } from "@better-auth/expo";
|
||||
import { Pool } from "pg";
|
||||
import { drizzleSchema } from "@money/shared/db";
|
||||
import { db } from "./db";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
database: drizzleAdapter(db, {
|
||||
schema: drizzleSchema,
|
||||
provider: "pg",
|
||||
usePlural: true,
|
||||
}),
|
||||
trustedOrigins: ["money://", "http://localhost:8081"],
|
||||
plugins: [
|
||||
|
||||
9
api/src/db.ts
Normal file
9
api/src/db.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { getDb } from "@money/shared/db";
|
||||
|
||||
if (!process.env.ZERO_UPSTREAM_DB) {
|
||||
throw new Error("ZERO_UPSTREAM_DB is not set");
|
||||
}
|
||||
|
||||
export const db = getDb({
|
||||
connectionString: process.env.ZERO_UPSTREAM_DB,
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
createMutators as createMutatorsShared,
|
||||
queries,
|
||||
schema,
|
||||
type Mutators,
|
||||
} from "@money/shared";
|
||||
import type { AuthData } from "@money/shared/auth";
|
||||
import { getHono } from "./hono";
|
||||
@@ -25,11 +26,18 @@ const processor = new PushProcessor(
|
||||
),
|
||||
);
|
||||
|
||||
const createMutators = (authData: AuthData | null) => {
|
||||
const mutators = createMutatorsShared(authData);
|
||||
return {
|
||||
...mutators,
|
||||
} as const satisfies Mutators;
|
||||
}
|
||||
|
||||
const zero = getHono()
|
||||
.post("/mutate", async (c) => {
|
||||
const authData = c.get("auth");
|
||||
|
||||
const result = await processor.process(createMutatorsShared(authData), c.req.raw);
|
||||
const result = await processor.process(createMutators(authData), c.req.raw);
|
||||
|
||||
return c.json(result);
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ export default function HomeScreen() {
|
||||
}
|
||||
const z = useZero<Schema, Mutators>();
|
||||
const [transactions] = useQuery(queries.allTransactions(session));
|
||||
const [user] = useQuery(queries.me(session));
|
||||
|
||||
const onNew = () => {
|
||||
z.mutate.transaction.create({
|
||||
@@ -22,10 +23,13 @@ export default function HomeScreen() {
|
||||
|
||||
return (
|
||||
<SafeAreaView>
|
||||
<Text>Hello {session?.user.name}</Text>
|
||||
<Text>Hello {user?.name}</Text>
|
||||
<Button onPress={onLogout} title="Logout" />
|
||||
<Text>Transactions: {JSON.stringify(transactions, null, 4)}</Text>
|
||||
<Button onPress={onNew} title="New" />
|
||||
<Button onPress={() => {
|
||||
z.mutate.transaction.deleteAll();
|
||||
}} title="Delete" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "expo lint"
|
||||
"lint": "expo lint",
|
||||
"db:migrate": "dotenv -- pnpm run --dir=shared db:migrate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/expo": "^1.3.27",
|
||||
@@ -19,6 +20,7 @@
|
||||
"@react-navigation/native": "^7.1.8",
|
||||
"@rocicorp/zero": "^0.23.2025090100",
|
||||
"better-auth": "^1.3.27",
|
||||
"drizzle-orm": "^0.44.6",
|
||||
"expo": "~54.0.13",
|
||||
"expo-constants": "~18.0.9",
|
||||
"expo-font": "~14.0.9",
|
||||
@@ -46,6 +48,8 @@
|
||||
"devDependencies": {
|
||||
"@types/pg": "^8.15.5",
|
||||
"@types/react": "~19.1.0",
|
||||
"dotenv-cli": "^10.0.0",
|
||||
"drizzle-kit": "^0.31.5",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-config-expo": "~10.0.0",
|
||||
"typescript": "~5.9.2"
|
||||
|
||||
578
pnpm-lock.yaml
generated
578
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1 +1,4 @@
|
||||
nodeLinker: hoisted
|
||||
packages:
|
||||
- 'api'
|
||||
- 'shared'
|
||||
|
||||
@@ -46,6 +46,13 @@ processes:
|
||||
condition: process_healthy
|
||||
zero:
|
||||
command: npx zero-cache-dev -p shared/src/schema.ts
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: process_completed_successfully
|
||||
|
||||
studio:
|
||||
command: npx drizzle-kit studio
|
||||
working_dir: ./shared
|
||||
depends_on:
|
||||
db:
|
||||
condition: process_healthy
|
||||
|
||||
14
shared/drizzle.config.ts
Normal file
14
shared/drizzle.config.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
if (!process.env.ZERO_UPSTREAM_DB) {
|
||||
throw new Error("ZERO_UPSTREAM_DB is not set");
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
schema: "./src/db/schema/index.ts",
|
||||
// out: "../migrations",
|
||||
dialect: "postgresql",
|
||||
dbCredentials: {
|
||||
url: process.env.ZERO_UPSTREAM_DB,
|
||||
},
|
||||
});
|
||||
@@ -5,6 +5,14 @@
|
||||
"private": true,
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./auth": "./src/auth.ts"
|
||||
"./auth": "./src/auth.ts",
|
||||
"./db": "./src/db/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"drizzle-zero": "^0.14.3"
|
||||
},
|
||||
"scripts": {
|
||||
"generate:zero": "drizzle-zero generate -s ./src/db/schema/public.ts -o ./src/zero-schema.gen.ts -f",
|
||||
"db:migrate": "drizzle-kit push"
|
||||
}
|
||||
}
|
||||
|
||||
10
shared/src/db/client.ts
Normal file
10
shared/src/db/client.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { drizzle } from "drizzle-orm/node-postgres";
|
||||
import { Pool } from "pg";
|
||||
import * as schema from "./schema";
|
||||
|
||||
export const getDb = ({ connectionString }: { connectionString: string }) => {
|
||||
const pool = new Pool({ connectionString, max: 5 });
|
||||
return drizzle(pool, {
|
||||
schema,
|
||||
});
|
||||
};
|
||||
6
shared/src/db/index.ts
Normal file
6
shared/src/db/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import * as drizzleSchema from "./schema";
|
||||
|
||||
export * from "./schema";
|
||||
export * from "./client";
|
||||
|
||||
export { drizzleSchema };
|
||||
2
shared/src/db/schema/index.ts
Normal file
2
shared/src/db/schema/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./public";
|
||||
export * from "./private";
|
||||
94
shared/src/db/schema/private.ts
Normal file
94
shared/src/db/schema/private.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import {
|
||||
index,
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { users } from "./public";
|
||||
|
||||
export const accounts = pgTable(
|
||||
"account",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
accountId: text("account_id").notNull(),
|
||||
providerId: text("provider_id").notNull(),
|
||||
accessToken: text("access_token"),
|
||||
refreshToken: text("refresh_token"),
|
||||
accessTokenExpiresAt: timestamp("access_token_expires_at"),
|
||||
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
|
||||
scope: text("scope"),
|
||||
idToken: text("id_token"),
|
||||
password: text("password"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("account_provider_account_unique").on(
|
||||
table.providerId,
|
||||
table.accountId,
|
||||
),
|
||||
index("account_user_id_idx").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
export const accountRelations = relations(accounts, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [accounts.userId],
|
||||
references: [users.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const sessions = pgTable(
|
||||
"session",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
token: text("token").notNull(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
ipAddress: text("ip_address"),
|
||||
userAgent: text("user_agent"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("session_token_unique").on(table.token),
|
||||
index("session_user_id_idx").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
export const sessionRelations = relations(sessions, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [sessions.userId],
|
||||
references: [users.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const verifications = pgTable(
|
||||
"verification",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expires_at").notNull(),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(table) => [index("verification_identifier_idx").on(table.identifier)],
|
||||
);
|
||||
|
||||
export const auditLogs = pgTable("audit_log", {
|
||||
id: text("id").primaryKey(),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
action: text("action").notNull(),
|
||||
});
|
||||
24
shared/src/db/schema/public.ts
Normal file
24
shared/src/db/schema/public.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { integer, pgTable, text, boolean, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
|
||||
export const users = pgTable(
|
||||
"user",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name"),
|
||||
email: text("email").notNull(),
|
||||
emailVerified: boolean("email_verified").notNull().default(false),
|
||||
image: text("image"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(table) => [uniqueIndex("user_email_unique").on(table.email)],
|
||||
);
|
||||
|
||||
export const transaction = pgTable("transaction", {
|
||||
id: text("id").primaryKey(),
|
||||
user_id: text("user_id").notNull(),
|
||||
name: text("name").notNull(),
|
||||
amount: integer("amount").notNull(),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export * from "./schema";
|
||||
export * from "./queries";
|
||||
export * from "./mutators";
|
||||
export * from "./zero-schema.gen";
|
||||
export * from "./zql";
|
||||
|
||||
@@ -16,6 +16,12 @@ export function createMutators(authData: AuthData | null) {
|
||||
name,
|
||||
amount,
|
||||
})
|
||||
},
|
||||
async deleteAll(tx: Tx) {
|
||||
const t = await tx.query.transaction.limit(10);
|
||||
for (const i of t) {
|
||||
await tx.mutate.transaction.delete({ id: i.id });
|
||||
}
|
||||
}
|
||||
}
|
||||
} as const;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { syncedQueryWithContext } from "@rocicorp/zero";
|
||||
import { z } from "zod";
|
||||
import { builder } from "@money/shared";
|
||||
import type { AuthData } from "./auth";
|
||||
import { type AuthData } from "./auth";
|
||||
import { isLoggedIn } from "./zql";
|
||||
|
||||
export const queries = {
|
||||
@@ -12,4 +12,10 @@ export const queries = {
|
||||
.limit(10)
|
||||
}
|
||||
),
|
||||
me: syncedQueryWithContext('me', z.tuple([]), (authData: AuthData | null) => {
|
||||
isLoggedIn(authData);
|
||||
return builder.users
|
||||
.where('id', '=', authData.user.id)
|
||||
.one();
|
||||
})
|
||||
};
|
||||
|
||||
@@ -1,31 +1,10 @@
|
||||
import { type Schema as ZeroSchema, createSchema, table, string, number, createBuilder, definePermissions } from "@rocicorp/zero";
|
||||
|
||||
const transaction = table('transaction')
|
||||
.columns({
|
||||
id: string(),
|
||||
user_id: string(),
|
||||
name: string(),
|
||||
amount: number(),
|
||||
})
|
||||
.primaryKey('id').schema;
|
||||
import { type Schema as ZeroSchema, definePermissions } from "@rocicorp/zero";
|
||||
import { schema as genSchema } from "./zero-schema.gen";
|
||||
|
||||
export const schema = {
|
||||
tables: { transaction },
|
||||
relationships: {},
|
||||
...genSchema,
|
||||
enableLegacyMutators: false,
|
||||
enableLegacyQueries: false,
|
||||
} satisfies ZeroSchema;
|
||||
|
||||
// export const schema = createSchema({
|
||||
// tables: [transaction],
|
||||
// enableLegacyMutators: false,
|
||||
// enableLegacyQueries: false,
|
||||
// });
|
||||
|
||||
export const builder = createBuilder(schema);
|
||||
|
||||
export const permissions = definePermissions(schema, () => ({}));
|
||||
|
||||
export type Schema = typeof schema;
|
||||
|
||||
|
||||
|
||||
165
shared/src/zero-schema.gen.ts
Normal file
165
shared/src/zero-schema.gen.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
/* eslint-disable */
|
||||
|
||||
// @ts-nocheck
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
// This file was automatically generated by drizzle-zero.
|
||||
// You should NOT make any changes in this file as it will be overwritten.
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import type { Row } from "@rocicorp/zero";
|
||||
import { createBuilder } from "@rocicorp/zero";
|
||||
import type { DrizzleToZeroSchema, ZeroCustomType } from "drizzle-zero";
|
||||
import type * as drizzleSchema from "./db/schema/public";
|
||||
|
||||
type ZeroSchema = DrizzleToZeroSchema<typeof drizzleSchema>;
|
||||
|
||||
/**
|
||||
* The Zero schema object.
|
||||
* This type is auto-generated from your Drizzle schema definition.
|
||||
*/
|
||||
export const schema = {
|
||||
tables: {
|
||||
transaction: {
|
||||
name: "transaction",
|
||||
columns: {
|
||||
id: {
|
||||
type: "string",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"transaction",
|
||||
"id"
|
||||
>,
|
||||
},
|
||||
user_id: {
|
||||
type: "string",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"transaction",
|
||||
"user_id"
|
||||
>,
|
||||
},
|
||||
name: {
|
||||
type: "string",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"transaction",
|
||||
"name"
|
||||
>,
|
||||
},
|
||||
amount: {
|
||||
type: "number",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"transaction",
|
||||
"amount"
|
||||
>,
|
||||
},
|
||||
},
|
||||
primaryKey: ["id"],
|
||||
},
|
||||
users: {
|
||||
name: "users",
|
||||
columns: {
|
||||
id: {
|
||||
type: "string",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"id"
|
||||
>,
|
||||
},
|
||||
name: {
|
||||
type: "string",
|
||||
optional: true,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"name"
|
||||
>,
|
||||
},
|
||||
email: {
|
||||
type: "string",
|
||||
optional: false,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"email"
|
||||
>,
|
||||
},
|
||||
emailVerified: {
|
||||
type: "boolean",
|
||||
optional: true,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"emailVerified"
|
||||
>,
|
||||
serverName: "email_verified",
|
||||
},
|
||||
image: {
|
||||
type: "string",
|
||||
optional: true,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"image"
|
||||
>,
|
||||
},
|
||||
createdAt: {
|
||||
type: "number",
|
||||
optional: true,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"createdAt"
|
||||
>,
|
||||
serverName: "created_at",
|
||||
},
|
||||
updatedAt: {
|
||||
type: "number",
|
||||
optional: true,
|
||||
customType: null as unknown as ZeroCustomType<
|
||||
ZeroSchema,
|
||||
"users",
|
||||
"updatedAt"
|
||||
>,
|
||||
serverName: "updated_at",
|
||||
},
|
||||
},
|
||||
primaryKey: ["id"],
|
||||
serverName: "user",
|
||||
},
|
||||
},
|
||||
relationships: {},
|
||||
enableLegacyQueries: true,
|
||||
enableLegacyMutators: true,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Represents the Zero schema type.
|
||||
* This type is auto-generated from your Drizzle schema definition.
|
||||
*/
|
||||
export type Schema = typeof schema;
|
||||
/**
|
||||
* Represents a row from the "transaction" table.
|
||||
* This type is auto-generated from your Drizzle schema definition.
|
||||
*/
|
||||
export type Transaction = Row<Schema["tables"]["transaction"]>;
|
||||
/**
|
||||
* Represents a row from the "users" table.
|
||||
* This type is auto-generated from your Drizzle schema definition.
|
||||
*/
|
||||
export type User = Row<Schema["tables"]["users"]>;
|
||||
|
||||
/**
|
||||
* Represents the Zero schema query builder.
|
||||
* This type is auto-generated from your Drizzle schema definition.
|
||||
*/
|
||||
export const builder = createBuilder(schema);
|
||||
Reference in New Issue
Block a user