Server Actions
- Alternativa a API endpoints
- Se ejecutan del lado del servidor
- Deben estar dentro de la carpeta src/actions/index.ts
- Si se definen en otro lugar, no son server actions
- El
inputes el objeto que se recibe en elhandlery el handler solo se ejecuta si todo el objeto es válido
Definición
src\actions\posts\get-post-likes.action.ts
import { defineAction } from "astro:actions";
import { z } from 'astro:schema';
import { db, eq, Posts } from "astro:db";
export const getPostLikes = defineAction({
input: z.string(),
handler: async (postId) => {
const [post] = await db.select().from(Posts).where(eq(Posts.id, postId));
if (!post) return { likes: 0, exists: false };
return {
likes: post.likes,
exists: true,
};
},
});
src\actions\index.ts
import { getGreeting } from "./greetings/get-greeting.action";
import { getPostLikes } from "./posts/get-post-likes.action";
import { updatePostLikes } from "./posts/update-post-likes.action";
export const server = {
getGreeting,
getPostLikes,
updatePostLikes,
};
Uso
src\components\likes\LikeCounterAction.svelte
import { actions } from "astro:actions";
const { data, error } = await actions.getGreeting({
name: "Astro",
age: 1,
isActive: true,
});
if (error) return alert(error.message);
console.log({ data });
src\components\likes\LikeCounterAction.svelte
<script lang="ts">
import { actions } from "astro:actions";
actions.updatePostLikes({
postId,
increment: likeClicks,
});
</script>