add mongoose orm to the stack builder (#191)

This commit is contained in:
José Alberto Gómez García
2025-05-02 15:23:04 +02:00
committed by GitHub
parent 946f3eb421
commit 437cf9a45a
15 changed files with 524 additions and 273 deletions

View File

@@ -0,0 +1,66 @@
{{#if (eq api "orpc")}}
import { z } from "zod";
import { publicProcedure } from "../lib/orpc";
import { Todo } from "../db/models/todo.model";
export const todoRouter = {
getAll: publicProcedure.handler(async () => {
return await Todo.find().lean();
}),
create: publicProcedure
.input(z.object({ text: z.string().min(1) }))
.handler(async ({ input }) => {
const newTodo = await Todo.create({ text: input.text });
return newTodo.toObject();
}),
toggle: publicProcedure
.input(z.object({ id: z.string(), completed: z.boolean() }))
.handler(async ({ input }) => {
await Todo.updateOne({ id: input.id }, { completed: input.completed });
return { success: true };
}),
delete: publicProcedure
.input(z.object({ id: z.string() }))
.handler(async ({ input }) => {
await Todo.deleteOne({ id: input.id });
return { success: true };
}),
};
{{/if}}
{{#if (eq api "trpc")}}
import { z } from "zod";
import { router, publicProcedure } from "../lib/trpc";
import { Todo } from "../db/models/todo.model";
export const todoRouter = router({
getAll: publicProcedure.query(async () => {
return await Todo.find().lean();
}),
create: publicProcedure
.input(z.object({ text: z.string().min(1) }))
.mutation(async ({ input }) => {
const newTodo = await Todo.create({ text: input.text });
return newTodo.toObject();
}),
toggle: publicProcedure
.input(z.object({ id: z.string(), completed: z.boolean() }))
.mutation(async ({ input }) => {
await Todo.updateOne({ id: input.id }, { completed: input.completed });
return { success: true };
}),
delete: publicProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input }) => {
await Todo.deleteOne({ id: input.id });
return { success: true };
}),
});
{{/if}}

View File

@@ -0,0 +1,24 @@
import mongoose from 'mongoose';
const { Schema, model } = mongoose;
const todoSchema = new Schema({
id: {
type: mongoose.Schema.Types.ObjectId,
auto: true,
},
text: {
type: String,
required: true,
},
completed: {
type: Boolean,
default: false,
},
}, {
collection: 'todo'
});
const Todo = model('Todo', todoSchema);
export { Todo };