This commit is contained in:
2025-03-06 20:50:31 +01:00
commit 4a1397651f
68 changed files with 10049 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
"use server";
import { articleSchema } from "@/lib/validation/zod/article";
import { api } from "@/trpc/server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
export async function createArticle(article: z.infer<typeof articleSchema>) {
const result = await api.article.create({
article,
});
if (!result[0]?.slug?.length) return false;
return redirect(`/artikel/${result[0].slug}/edit`);
}
export async function updateArticle(
article: z.infer<typeof articleSchema>,
articleId: string,
) {
const result = await api.article.update({
article,
articleId,
});
// if (!result[0]?.id?.length) return false;
// return revalidatePath(`/artikel/${result[0].id}/edit`);
}
export async function deleteArticle(articleId: string) {
const result = await api.article.delete({
articleId,
});
// if (!result[0]?.id?.length) return false;
}
+31
View File
@@ -0,0 +1,31 @@
"use server";
import { categorySchema } from "@/lib/validation/zod/category";
import { api } from "@/trpc/server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
export async function createCategory(category: z.infer<typeof categorySchema>) {
const result = await api.category.create({
category,
});
if (!result[0]?.slug?.length) return false;
return redirect(`/kategorie/${result[0].slug}/edit`);
}
export async function updateCategory(
category: z.infer<typeof categorySchema>,
categoryId: string,
) {
const result = await api.category.update({
category,
categoryId,
});
// if (!result[0]?.id?.length) return false;
// return revalidatePath(`/artikel/${result[0].id}/edit`);
}
export async function deleteCategory(categoryId: string) {
const result = await api.category.delete({
categoryId,
});
}
+25
View File
@@ -0,0 +1,25 @@
import { articleRouter } from "./routers/article";
import { categoryRouter } from "@/server/api/routers/category";
import { createCallerFactory, createTRPCRouter } from "@/server/api/trpc";
/**
* This is the primary router for your server.
*
* All routers added in /api/routers should be manually added here.
*/
export const appRouter = createTRPCRouter({
article: articleRouter,
category: categoryRouter,
});
// export type definition of API
export type AppRouter = typeof appRouter;
/**
* Create a server-side caller for the tRPC API.
* @example
* const trpc = createCaller(createContext);
* const res = await trpc.post.all();
* ^? Post[]
*/
export const createCaller = createCallerFactory(appRouter);
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
import {
createTRPCRouter,
protectedProcedure,
publicProcedure,
} from "@/server/api/trpc";
import { articles } from "@/server/db/schema";
import { articleSchema } from "@/lib/validation/zod/article";
import { eq } from "drizzle-orm";
import { hasPermission, Role } from "@/lib/validation/has-permission";
import { generateSlug } from "@/lib/utils";
export const articleRouter = createTRPCRouter({
get: publicProcedure
.input(z.object({ slug: z.string() }))
.query(async ({ ctx, input }) => {
return await ctx.db.query.articles.findFirst({
where: eq(articles.slug, input.slug),
});
}),
getAll: publicProcedure
.input(z.object({ categoryId: z.string() }).optional())
.query(async ({ ctx, input }) => {
return await ctx.db.query.articles.findMany({
where: input?.categoryId
? eq(articles.categoryId, input.categoryId)
: undefined,
});
}),
getAllPreviews: publicProcedure
.input(z.object({ categoryId: z.string() }).optional())
.query(async ({ ctx, input }) => {
return await ctx.db.query.articles.findMany({
where: input?.categoryId
? eq(articles.categoryId, input.categoryId)
: undefined,
columns: {
title: true,
slug: true,
createdAt: true,
},
});
}),
create: protectedProcedure
.input(z.object({ article: articleSchema }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to create articles");
}
const slug = generateSlug(input.article.title);
return await ctx.db
.insert(articles)
.values({ ...input.article, slug })
.returning({
slug: articles.slug,
});
}),
update: protectedProcedure
.input(z.object({ article: articleSchema, articleId: z.string() }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to update articles");
}
return await ctx.db
.update(articles)
.set(input.article)
.where(eq(articles.id, input.articleId))
.returning({
id: articles.id,
});
}),
delete: protectedProcedure
.input(z.object({ articleId: z.string() }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to delete articles");
}
return await ctx.db
.delete(articles)
.where(eq(articles.id, input.articleId))
.returning({
id: articles.id,
});
}),
});
+71
View File
@@ -0,0 +1,71 @@
import { z } from "zod";
import {
createTRPCRouter,
protectedProcedure,
publicProcedure,
} from "@/server/api/trpc";
import { categories } from "@/server/db/schema";
import { eq } from "drizzle-orm";
import { hasPermission, Role } from "@/lib/validation/has-permission";
import { categorySchema } from "@/lib/validation/zod/category";
import { generateSlug } from "@/lib/utils";
export const categoryRouter = createTRPCRouter({
get: publicProcedure
.input(z.object({ slug: z.string() }))
.query(async ({ ctx, input }) => {
return await ctx.db.query.categories.findFirst({
where: eq(categories.slug, input.slug),
});
}),
getAll: publicProcedure.query(async ({ ctx }) => {
return await ctx.db.query.categories.findMany();
}),
create: protectedProcedure
.input(z.object({ category: categorySchema }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to create categories");
}
const slug = generateSlug(input.category.name);
return await ctx.db
.insert(categories)
.values({ ...input.category, slug })
.returning({
slug: categories.slug,
});
}),
update: protectedProcedure
.input(z.object({ category: categorySchema, categoryId: z.string() }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to update categories");
}
return await ctx.db
.update(categories)
.set(input.category)
.where(eq(categories.id, input.categoryId))
.returning({
id: categories.id,
});
}),
delete: protectedProcedure
.input(z.object({ categoryId: z.string() }))
.mutation(async ({ ctx, input }) => {
const isEditor = hasPermission(ctx.session.user.role, Role.EDITOR);
if (!isEditor) {
throw new Error("You are not allowed to delete articles");
}
return await ctx.db
.delete(categories)
.where(eq(categories.id, input.categoryId))
.returning({
id: categories.id,
});
}),
});
+133
View File
@@ -0,0 +1,133 @@
/**
* YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS:
* 1. You want to modify request context (see Part 1).
* 2. You want to create a new middleware or type of procedure (see Part 3).
*
* TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will
* need to use are documented accordingly near the end.
*/
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
import { auth } from "@/server/auth";
import { db } from "@/server/db";
/**
* 1. CONTEXT
*
* This section defines the "contexts" that are available in the backend API.
*
* These allow you to access things when processing a request, like the database, the session, etc.
*
* This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
* wrap this and provides the required context.
*
* @see https://trpc.io/docs/server/context
*/
export const createTRPCContext = async (opts: { headers: Headers }) => {
const session = await auth();
return {
db,
session,
...opts,
};
};
/**
* 2. INITIALIZATION
*
* This is where the tRPC API is initialized, connecting the context and transformer. We also parse
* ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
* errors on the backend.
*/
const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
},
};
},
});
/**
* Create a server-side caller.
*
* @see https://trpc.io/docs/server/server-side-calls
*/
export const createCallerFactory = t.createCallerFactory;
/**
* 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
*
* These are the pieces you use to build your tRPC API. You should import these a lot in the
* "/src/server/api/routers" directory.
*/
/**
* This is how you create new routers and sub-routers in your tRPC API.
*
* @see https://trpc.io/docs/router
*/
export const createTRPCRouter = t.router;
/**
* Middleware for timing procedure execution and adding an artificial delay in development.
*
* You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
* network latency that would occur in production but not in local development.
*/
const timingMiddleware = t.middleware(async ({ next, path }) => {
const start = Date.now();
if (t._config.isDev) {
// artificial delay in dev
const waitMs = Math.floor(Math.random() * 400) + 100;
await new Promise((resolve) => setTimeout(resolve, waitMs));
}
const result = await next();
const end = Date.now();
console.log(`[TRPC] ${path} took ${end - start}ms to execute`);
return result;
});
/**
* Public (unauthenticated) procedure
*
* This is the base piece you use to build new queries and mutations on your tRPC API. It does not
* guarantee that a user querying is authorized, but you can still access user session data if they
* are logged in.
*/
export const publicProcedure = t.procedure.use(timingMiddleware);
/**
* Protected (authenticated) procedure
*
* If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
* the session is valid and guarantees `ctx.session.user` is not null.
*
* @see https://trpc.io/docs/procedures
*/
export const protectedProcedure = t.procedure
.use(timingMiddleware)
.use(({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
// infers the `session` as non-nullable
session: { ...ctx.session, user: ctx.session.user },
},
});
});
+68
View File
@@ -0,0 +1,68 @@
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { type DefaultSession, type NextAuthConfig } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import { db } from "@/server/db";
import {
accounts,
sessions,
users,
verificationTokens,
} from "@/server/db/schema";
import { Adapter } from "next-auth/adapters";
/**
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
* object and keep type safety.
*
* @see https://next-auth.js.org/getting-started/typescript#module-augmentation
*/
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
// ...other properties
role: UserRole;
} & DefaultSession["user"];
}
interface User {
// ...other properties
role: UserRole;
}
}
/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
* @see https://next-auth.js.org/configuration/options
*/
export const authConfig = {
providers: [
DiscordProvider,
/**
* ...add more providers here.
*
* Most other providers require a bit more work than the Discord provider. For example, the
* GitHub provider requires you to add the `refresh_token_expires_in` field to the Account
* model. Refer to the NextAuth.js docs for the provider you want to use. Example:
*
* @see https://next-auth.js.org/providers/github
*/
],
adapter: DrizzleAdapter(db, {
usersTable: users,
accountsTable: accounts,
sessionsTable: sessions,
verificationTokensTable: verificationTokens,
}) as Adapter,
callbacks: {
session: ({ session, user }) => ({
...session,
user: {
...session.user,
id: user.id,
},
}),
},
} satisfies NextAuthConfig;
+10
View File
@@ -0,0 +1,10 @@
import NextAuth from "next-auth";
import { cache } from "react";
import { authConfig } from "./config";
const { auth: uncachedAuth, handlers, signIn, signOut } = NextAuth(authConfig);
const auth = cache(uncachedAuth);
export { auth, handlers, signIn, signOut };
+18
View File
@@ -0,0 +1,18 @@
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { env } from "@/env";
import * as schema from "./schema";
/**
* Cache the database connection in development. This avoids creating a new connection on every HMR
* update.
*/
const globalForDb = globalThis as unknown as {
conn: postgres.Sql | undefined;
};
const conn = globalForDb.conn ?? postgres(env.DATABASE_URL);
if (env.NODE_ENV !== "production") globalForDb.conn = conn;
export const db = drizzle(conn, { schema });
+168
View File
@@ -0,0 +1,168 @@
import { createId } from "@paralleldrive/cuid2";
import { relations, sql } from "drizzle-orm";
import {
index,
integer,
pgTableCreator,
primaryKey,
text,
timestamp,
varchar,
} from "drizzle-orm/pg-core";
import { type AdapterAccount } from "next-auth/adapters";
/**
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
* database instance for multiple projects.
*
* @see https://orm.drizzle.team/docs/goodies#multi-project-schema
*/
export const createTable = pgTableCreator((name) => `wiki-antifa_${name}`);
export const articles = createTable(
"article",
{
id: varchar("id", { length: 255 })
.primaryKey()
.$defaultFn(() => createId())
.notNull(),
title: varchar("title", { length: 256 }),
slug: varchar("slug", { length: 256 }).unique(),
authorId: varchar("author_id", { length: 255 }),
content: text("content"),
categoryId: varchar("category_id", { length: 255 }),
createdAt: timestamp("created_at", { withTimezone: true })
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
() => new Date(),
),
},
(example) => ({
articleTitleIndex: index("article_title_idx").on(example.title),
}),
);
export type Article = typeof articles.$inferSelect;
export const articleRelations = relations(articles, ({ one }) => ({
categories: one(categories, {
fields: [articles.categoryId],
references: [categories.id],
}),
}));
export const categories = createTable(
"category",
{
id: varchar("id", { length: 255 })
.primaryKey()
.$defaultFn(() => createId())
.notNull(),
name: varchar("name", { length: 256 }),
slug: varchar("slug", { length: 256 }).unique(),
createdAt: timestamp("created_at", { withTimezone: true })
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).$onUpdate(
() => new Date(),
),
},
(example) => ({
categoryNameIndex: index("category_name_idx").on(example.name),
}),
);
export type Category = typeof categories.$inferSelect;
export const categoryRelations = relations(categories, ({ many }) => ({
articles: many(articles),
}));
export const users = createTable("user", {
id: varchar("id", { length: 255 })
.notNull()
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
role: integer("role").default(1).notNull(),
emailVerified: timestamp("email_verified", {
mode: "date",
withTimezone: true,
}).default(sql`CURRENT_TIMESTAMP`),
image: varchar("image", { length: 255 }),
});
export const usersRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
}));
export const accounts = createTable(
"account",
{
userId: varchar("user_id", { length: 255 })
.notNull()
.references(() => users.id),
type: varchar("type", { length: 255 })
.$type<AdapterAccount["type"]>()
.notNull(),
provider: varchar("provider", { length: 255 }).notNull(),
providerAccountId: varchar("provider_account_id", {
length: 255,
}).notNull(),
refresh_token: text("refresh_token"),
access_token: text("access_token"),
expires_at: integer("expires_at"),
token_type: varchar("token_type", { length: 255 }),
scope: varchar("scope", { length: 255 }),
id_token: text("id_token"),
session_state: varchar("session_state", { length: 255 }),
},
(account) => ({
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
userIdIdx: index("account_user_id_idx").on(account.userId),
}),
);
export const accountsRelations = relations(accounts, ({ one }) => ({
user: one(users, { fields: [accounts.userId], references: [users.id] }),
}));
export const sessions = createTable(
"session",
{
sessionToken: varchar("session_token", { length: 255 })
.notNull()
.primaryKey(),
userId: varchar("user_id", { length: 255 })
.notNull()
.references(() => users.id),
expires: timestamp("expires", {
mode: "date",
withTimezone: true,
}).notNull(),
},
(session) => ({
userIdIdx: index("session_user_id_idx").on(session.userId),
}),
);
export const sessionsRelations = relations(sessions, ({ one }) => ({
user: one(users, { fields: [sessions.userId], references: [users.id] }),
}));
export const verificationTokens = createTable(
"verification_token",
{
identifier: varchar("identifier", { length: 255 }).notNull(),
token: varchar("token", { length: 255 }).notNull(),
expires: timestamp("expires", {
mode: "date",
withTimezone: true,
}).notNull(),
},
(vt) => ({
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
}),
);