Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
391 changes: 279 additions & 112 deletions frontend/package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
},
"dependencies": {
"next": "16.4.6",
"pg": "^8.23.1",
"react": "19.3.0",
"react-dom": "19.3.0"
"react-dom": "19.3.0",
"server-only": "^0.0.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/pg": "^8.23.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/app/api/catalog/individuals/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { catalogGateway } from "@/lib/catalog";
import { parseCatalogQuery, type RawCatalogParams } from "@/lib/catalog/params";
import type { CatalogErrorBody } from "@/types/catalog";

export async function GET(request: Request): Promise<Response> {
const params = Object.fromEntries(
new URL(request.url).searchParams.entries(),
) as RawCatalogParams;
const query = parseCatalogQuery(params);

try {
const page = await catalogGateway.list(query);
return Response.json(page, {
headers: { "Cache-Control": "private, no-store" },
});
} catch (error) {
console.error("catalog: lecture impossible", error);
const body: CatalogErrorBody = {
code: "UPSTREAM_UNAVAILABLE",
message: "Le catalogue est temporairement indisponible.",
};
return Response.json(body, { status: 503 });
}
}
6 changes: 6 additions & 0 deletions frontend/src/lib/catalog/gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { CatalogPage, CatalogQuery } from "@/types/catalog";

// L'affichage dépend de cette interface, jamais de PostgreSQL ni de Next.
export interface CatalogGateway {
list(query: CatalogQuery): Promise<CatalogPage>;
}
5 changes: 5 additions & 0 deletions frontend/src/lib/catalog/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { postgresGateway } from "./postgres-gateway";

export const catalogGateway = postgresGateway;

export type { CatalogGateway } from "./gateway";
38 changes: 38 additions & 0 deletions frontend/src/lib/catalog/params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { CatalogQuery, CatalogSort } from "@/types/catalog";

export const CATALOG_PAGE_SIZE = 15;

export type RawCatalogParams = Record<string, string | string[] | undefined>;

const DEFAULT_SORT: CatalogSort = "lastObservation";

function first(value: string | string[] | undefined): string {
return Array.isArray(value) ? (value[0] ?? "") : (value ?? "");
}

function positiveInteger(value: string, fallback: number): number {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
}

export function parseCatalogQuery(params: RawCatalogParams): CatalogQuery {
const sort = first(params.sort);
const page = positiveInteger(first(params.page), 1);

return {
search: first(params.search).trim(),
sort: sort === "lastObservation" ? sort : DEFAULT_SORT,
page,
pageSize: CATALOG_PAGE_SIZE,
};
}

export function buildCatalogUrl(query: CatalogQuery): string {
const params = new URLSearchParams({
search: query.search,
sort: query.sort,
page: String(query.page),
pageSize: String(query.pageSize),
});
return `/catalogue?${params.toString()}`;
}
102 changes: 102 additions & 0 deletions frontend/src/lib/catalog/postgres-gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import "server-only";

import { Pool } from "pg";

import type { CatalogGateway } from "./gateway";
import type {
CatalogIndividual,
CatalogPage,
CatalogQuery,
} from "@/types/catalog";

type IndividualRow = {
code: string;
photo_id: number;
};

const LIST_SQL = `
with reference as (
select distinct on (p.individual_id)
p.individual_id,
p.id as photo_id
from photos p
order by p.individual_id,
case p.side when 'D' then 0 when 'G' then 1 else 2 end,
p.date desc nulls last,
p.id
),
activity as (
select individual_id,
max(date) as last_observation_date
from photos
group by individual_id
)
select i.code, r.photo_id
from individuals i
join reference r on r.individual_id = i.id
left join activity a on a.individual_id = i.id
where $1 = '' or i.code ilike '%' || $1 || '%'
order by a.last_observation_date desc nulls last, i.code
limit $2 offset $3
`;

const COUNT_SQL = `
select count(*)::int as total
from individuals i
where $1 = '' or i.code ilike '%' || $1 || '%'
`;

let pool: Pool | undefined;

function getPool(): Pool {
if (!process.env.DATABASE_URL) {
throw new Error("DATABASE_URL est requise pour lire le catalogue");
}
pool ??= new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
max: 2,
});
return pool;
}

function toIndividual(row: IndividualRow): CatalogIndividual {
const photoId = String(row.photo_id);
return {
code: row.code,
photo: {
id: photoId,
url: `/api/catalog/photos/${photoId}`,
alt: `Photo de ${row.code}`,
},
observationsLabel: "X observations",
};
}

export const postgresGateway: CatalogGateway = {
async list(query: CatalogQuery): Promise<CatalogPage> {
const client = await getPool().connect();
try {
const offset = (query.page - 1) * query.pageSize;
const [rows, totals] = await Promise.all([
client.query<IndividualRow>(LIST_SQL, [
query.search,
query.pageSize,
offset,
]),
client.query<{ total: number }>(COUNT_SQL, [query.search]),
]);
const total = totals.rows[0]?.total ?? 0;

return {
items: rows.rows.map(toIndividual),
total,
page: query.page,
pageSize: query.pageSize,
totalPages: Math.ceil(total / query.pageSize) || 1,
};
} finally {
client.release();
}
},
};
33 changes: 33 additions & 0 deletions frontend/src/types/catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
export type CatalogSort = "lastObservation";

export type CatalogQuery = {
search: string;
sort: CatalogSort;
page: number;
pageSize: number;
};

export type CatalogPhoto = {
id: string;
url: string;
alt: string;
};

export type CatalogIndividual = {
code: string;
photo: CatalogPhoto;
observationsLabel: string;
};

export type CatalogPage = {
items: readonly CatalogIndividual[];
total: number;
page: number;
pageSize: number;
totalPages: number;
};

export type CatalogErrorBody = {
code: "INVALID_QUERY" | "UPSTREAM_UNAVAILABLE";
message: string;
};
Loading