nuxt-users
Version:
A comprehensive user management module for Nuxt 3 and Nuxt 4 applications with authentication, authorization, database support, and CLI tools
60 lines (59 loc) • 2.08 kB
JavaScript
import { createError, defineEventHandler, getQuery } from "h3";
import { useRuntimeConfig } from "#imports";
import { useDb } from "../../utils/db.js";
import { getLastLoginTime } from "../../utils/user.js";
export default defineEventHandler(async (event) => {
const { nuxtUsers } = useRuntimeConfig();
const options = nuxtUsers;
const db = await useDb(options);
const usersTable = options.tables.users;
const query = getQuery(event);
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const offset = (page - 1) * limit;
if (page < 1 || limit < 1 || limit > 100) {
throw createError({
statusCode: 400,
statusMessage: "Invalid pagination parameters. Page must be >= 1, limit must be between 1 and 100."
});
}
try {
const countResult = await db.sql`SELECT COUNT(*) as total FROM {${usersTable}} WHERE active = FALSE`;
const total = countResult.rows[0]?.total ?? 0;
const usersResult = await db.sql`
SELECT id, email, name, role, created_at, updated_at
FROM {${usersTable}}
WHERE active = FALSE
ORDER BY name ASC
LIMIT ${limit} OFFSET ${offset}
`;
const users = await Promise.all(usersResult.rows.map(async (user) => {
const lastLoginTime = await getLastLoginTime(user.id, options);
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
created_at: user.created_at instanceof Date ? user.created_at.toISOString() : user.created_at,
updated_at: user.updated_at instanceof Date ? user.updated_at.toISOString() : user.updated_at,
last_login_at: lastLoginTime
};
}));
return {
users,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
hasNext: page * limit < total,
hasPrev: page > 1
}
};
} catch (error) {
throw createError({
statusCode: 500,
statusMessage: `Error fetching users: ${error instanceof Error ? error.message : String(error)}`
});
}
});