feat: integrate Gitea API for user management and add error handling

This commit is contained in:
ngc2207 2024-12-01 22:12:55 +08:00
parent 8dc72f7e29
commit 1acee31432
4 changed files with 62 additions and 0 deletions

View File

@ -1,7 +1,14 @@
import logger from "@/lib/logger";
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
/* config options here */ /* config options here */
serverExternalPackages: ["pino", "pino-pretty"],
}; };
if (!process.env.GITEA_URL || !process.env.GITEA_TOKEN) {
logger.error("GITEA_URL and GITEA_TOKEN must be set in your .env file");
throw new Error("GITEA_URL and GITEA_TOKEN must be set in your .env file");
}
export default nextConfig; export default nextConfig;

View File

@ -9,8 +9,11 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-slot": "^1.1.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cross-fetch": "^4.0.0",
"gitea-js": "^1.22.0",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"next": "15.0.3", "next": "15.0.3",
"pino": "^9.5.0", "pino": "^9.5.0",

View File

@ -0,0 +1,17 @@
"use server";
import { APIError, CreateUserOption, User } from "gitea-js";
import { callGiteaApi, gitea, GiteaApiResponse } from "@/lib/gitea";
export async function adminCreateUser(
body: CreateUserOption
): Promise<GiteaApiResponse<User, APIError>> {
const context = { body };
const result = await callGiteaApi(
() => gitea.admin.adminCreateUser(body),
"Successfully created user",
"Failed to create user",
context
);
return result;
}

35
src/lib/gitea.ts Normal file
View File

@ -0,0 +1,35 @@
import logger from "./logger";
import fetch from "cross-fetch";
import { APIError, giteaApi } from "gitea-js";
const gitea = giteaApi(process.env.GITEA_URL as string, {
token: process.env.GITEA_TOKEN,
customFetch: fetch,
});
interface GiteaApiResponse<D, E> {
data: D | null;
error: E | null;
}
async function callGiteaApi<D>(
apiCall: () => Promise<GiteaApiResponse<D, APIError>>,
successMessage: string,
errorMessage: string,
context?: Record<string, unknown>
): Promise<GiteaApiResponse<D, APIError>> {
try {
logger.info("Calling Gitea API");
const response = await apiCall();
logger.info({ context, response }, successMessage);
return { data: response.data, error: response.error };
} catch (err) {
logger.error({ context, error: err }, errorMessage);
const errorResponse = err as GiteaApiResponse<null, APIError>;
const apiError = errorResponse.error;
return { data: errorResponse.data, error: apiError };
}
}
export { gitea, callGiteaApi };
export type { GiteaApiResponse };