• Fri. Mar 21st, 2025

Astro with HTMX: Server-side rendering made easy

By

Mar 20, 2025



$ npx astro add node

Services

Let’s start building our custom code at the service layer. The service layer gives us a central place to put all our middleware that can be reused across the app. In a real application, the service layer would interact with a data store via a data layer, but for our exploration we can just us in-memory data.

The convention in Astro seems to be to use a /lib directory for these types of things. All the code for Astro goes in the /src directory, so we’ll have our service code at src/lib/todo.js:

src/lib/todo.js:

// src/lib/todo.js
let todosData = [
{ id: 1, text: “Learn Kung Fu”, completed: false },
{ id: 2, text: “Watch Westminster”, completed: true },
{ id: 3, text: “Study Vedanta”, completed: false },
];

export async function getTodos() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(todosData);
}, 100); // Simulate a slight delay for fetching
});
}

export async function deleteTodo(id) {
return new Promise((resolve) => {
setTimeout(() => {
todosData = todosData.filter(todo => todo.id !== id); resolve(true);
}, 100);
});
}
export async function addTodo(text) {
return new Promise((resolve) => {
setTimeout(() => {
const newTodo = { id: todosData.length+1, text, completed: false }; todosData.push(newTodo);
resolve(newTodo);
}, 100);
});
}

One thing to notice in general is that all our functions return promises. This is something Astro supports out of the box and is excellent for these service methods when they need to talk to a datastore, to avoid blocking on those network calls. In our case, we simulate a network delay with a timeout.



Source link