Pocty zaznamu a vetsi stranky z Service Layeru

- GET /api/entities/{set}/$count a /api/<resource>/$count: pocet zaznamu
  jednim volanim SAPu, podporuje $filter, vraci { count }
- $inlinecount=allpages (alias $count=true) se predava do Service Layeru
- /all posila Prefer: odata.maxpagesize podle SAP_B1_PAGE_SIZE (vychozi 500)
  misto vychozich 20 zaznamu na stranku
- Swagger, README, .env.example, dokumentace a testy
This commit is contained in:
JiriUhlir
2026-12-03 12:48:11 +01:00
parent 6924459aac
commit f7b127c94a
10 changed files with 196 additions and 8 deletions
+2
View File
@@ -9,6 +9,8 @@ SAP_B1_TIMEOUT_MS=30000
SAP_B1_REJECT_UNAUTHORIZED=true SAP_B1_REJECT_UNAUTHORIZED=true
SAP_B1_RETRY_COUNT=2 SAP_B1_RETRY_COUNT=2
SAP_B1_RETRY_DELAY_MS=250 SAP_B1_RETRY_DELAY_MS=250
# Pocet zaznamu na stranku pro /all (hlavicka Prefer: odata.maxpagesize), vychozi 500.
SAP_B1_PAGE_SIZE=500
# Volitelny sdileny klic pro /api routy; kdyz je nastaveny, kazdy request # Volitelny sdileny klic pro /api routy; kdyz je nastaveny, kazdy request
# musi poslat hlavicku X-Api-Key se stejnou hodnotou. # musi poslat hlavicku X-Api-Key se stejnou hodnotou.
+5
View File
@@ -18,9 +18,11 @@ Součástí repozitáře je AppFactory HTTP wrapper s endpointy:
- `GET /api/system/info` (verze SAP, dostupné entity sety, UDF/UDT/UDO, admin info) - `GET /api/system/info` (verze SAP, dostupné entity sety, UDF/UDT/UDO, admin info)
- `GET /api/entities` (seznam všech entity setů) - `GET /api/entities` (seznam všech entity setů)
- `GET|POST /api/entities/{entitySet}`, `GET /api/entities/{entitySet}/all` - `GET|POST /api/entities/{entitySet}`, `GET /api/entities/{entitySet}/all`
- `GET /api/entities/{entitySet}/$count` (počet záznamů jedním voláním SAPu, volitelně s `$filter`)
- `GET|PATCH|DELETE /api/entities/{entitySet}/{id}` (`?idType=number` pro číselné klíče) - `GET|PATCH|DELETE /api/entities/{entitySet}/{id}` (`?idType=number` pro číselné klíče)
- `GET /api/<resource>` - `GET /api/<resource>`
- `GET /api/<resource>/all` - `GET /api/<resource>/all`
- `GET /api/<resource>/$count`
- `GET /api/<resource>/{id}` - `GET /api/<resource>/{id}`
- `POST /api/<resource>` - `POST /api/<resource>`
- `PATCH /api/<resource>/{id}` - `PATCH /api/<resource>/{id}`
@@ -48,11 +50,14 @@ SAP_B1_TIMEOUT_MS=30000
SAP_B1_REJECT_UNAUTHORIZED=true SAP_B1_REJECT_UNAUTHORIZED=true
SAP_B1_RETRY_COUNT=2 SAP_B1_RETRY_COUNT=2
SAP_B1_RETRY_DELAY_MS=250 SAP_B1_RETRY_DELAY_MS=250
SAP_B1_PAGE_SIZE=500
API_KEY=<volitelny secret> API_KEY=<volitelny secret>
``` ```
`SAP_B1_BASE_URL` může být buď root Service Layer hostu, nebo přímo URL končící `/b1s/v1`. Pro self-signed certifikáty lze v interním prostředí nastavit `SAP_B1_REJECT_UNAUTHORIZED=false`; v produkci preferuj důvěryhodný certifikát a ponech `true`. `SAP_B1_BASE_URL` může být buď root Service Layer hostu, nebo přímo URL končící `/b1s/v1`. Pro self-signed certifikáty lze v interním prostředí nastavit `SAP_B1_REJECT_UNAUTHORIZED=false`; v produkci preferuj důvěryhodný certifikát a ponech `true`.
`SAP_B1_PAGE_SIZE` je počet záznamů na stránku, o který si `/all` říká Service Layeru hlavičkou `Prefer: odata.maxpagesize` (výchozí 500). Bez ní Service Layer vrací jen 20 záznamů na stránku.
## Autentizace HTTP API ## Autentizace HTTP API
SAP credentials jsou vnitřní secret služby — klienti je neposílají. Když je nastavený secret `API_KEY`, musí každý request na `/api/...` obsahovat hlavičku: SAP credentials jsou vnitřní secret služby — klienti je neposílají. Když je nastavený secret `API_KEY`, musí každý request na `/api/...` obsahovat hlavičku:
@@ -45,6 +45,19 @@ Bezpečnostní pravidla:
(chyba je v odpovědi vidět, nejde o tiché selhání). (chyba je v odpovědi vidět, nejde o tiché selhání).
- **Stránkování** – následuje `odata.nextLink` i `@odata.nextLink`. U absolutních - **Stránkování** – následuje `odata.nextLink` i `@odata.nextLink`. U absolutních
nextLinků se zachová i query string (`$skip` apod.), takže `listAll` nezacyklí. nextLinků se zachová i query string (`$skip` apod.), takže `listAll` nezacyklí.
`/all` posílá na každou stránku hlavičku `Prefer: odata.maxpagesize=<SAP_B1_PAGE_SIZE>`
(výchozí 500). Bez ní Service Layer vrací 20 záznamů na stránku, takže např. 2231
zákazníků stálo 112 volání SAPu, s hodnotou 500 je to 5 volání.
- **Počty záznamů** - dvě možnosti:
- `GET /api/entities/{entitySet}/$count` a `GET /api/<resource>/$count` volají
`GET /b1s/v1/{entitySet}/$count` (jedno volání SAPu), podporují `$filter` a vrací
`{ "count": 2231 }`. Routa je registrovaná před `/{id}`, jinak by se `$count` četlo
jako klíč. Express 4 bere `$` v textové cestě jako kotvu regexu, proto jsou tyto routy
zapsané jako RegExp; přijímají i zakódované `%24count`.
- U výpisu `$inlinecount=allpages` (nebo OData v4 alias `$count=true`) se předá do
Service Layeru a ten vrátí celkový počet v `odata.count` vedle první stránky.
- **Verze Service Layeru** - connector pracuje jen s `/b1s/v1` (OData v3), `/b1s/v2` není
podporované.
## Reverse proxy a Swagger ## Reverse proxy a Swagger
+13 -2
View File
@@ -3,7 +3,7 @@ import https from "node:https";
import axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios"; import axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios";
import { z } from "zod"; import { z } from "zod";
import { SapB1LoginInfo, SessionManager } from "../auth/SessionManager"; import { SapB1LoginInfo, SessionManager } from "../auth/SessionManager";
import { SapB1Config, SapB1ConfigSchema } from "../config"; import { DEFAULT_PAGE_SIZE, SapB1Config, SapB1ConfigSchema } from "../config";
import { SapB1Error, toSapB1Error } from "../errors/SapB1Error"; import { SapB1Error, toSapB1Error } from "../errors/SapB1Error";
import { ODataQuery, ODataResponse } from "../types/odata"; import { ODataQuery, ODataResponse } from "../types/odata";
import { buildODataParams, extractNextLink } from "./odata"; import { buildODataParams, extractNextLink } from "./odata";
@@ -50,6 +50,14 @@ export class SapB1Client {
return this.request<T>("GET", path, undefined, { params: buildODataParams(query), schema }); return this.request<T>("GET", path, undefined, { params: buildODataParams(query), schema });
} }
// Service Layer answers GET /{set}/$count with a bare number; only $filter applies to it.
public count(path: string, filter?: string): Promise<number> {
return this.request<number>("GET", `${path}/$count`, undefined, {
params: buildODataParams(filter ? { filter } : {}),
schema: z.coerce.number().int().min(0)
});
}
public post<T>(path: string, data?: unknown, schema?: z.ZodType<T>): Promise<T> { public post<T>(path: string, data?: unknown, schema?: z.ZodType<T>): Promise<T> {
return this.request<T>("POST", path, data, { schema }); return this.request<T>("POST", path, data, { schema });
} }
@@ -68,7 +76,10 @@ export class SapB1Client {
let nextQuery: ODataQuery | undefined = query; let nextQuery: ODataQuery | undefined = query;
while (nextPath) { while (nextPath) {
const response: ODataResponse<T> = await this.get<ODataResponse<T>>(nextPath, nextQuery); const response: ODataResponse<T> = await this.request<ODataResponse<T>>("GET", nextPath, undefined, {
params: buildODataParams(nextQuery),
headers: { Prefer: `odata.maxpagesize=${this.config.pageSize ?? DEFAULT_PAGE_SIZE}` }
});
const value = schema ? z.array(schema).parse(response.value) : response.value; const value = schema ? z.array(schema).parse(response.value) : response.value;
items.push(...value); items.push(...value);
const nextLink: string | undefined = extractNextLink(response); const nextLink: string | undefined = extractNextLink(response);
+4
View File
@@ -24,6 +24,10 @@ export function buildODataParams(query: ODataQuery = {}): Record<string, string
params.$orderby = Array.isArray(parsed.orderby) ? parsed.orderby.join(",") : parsed.orderby; params.$orderby = Array.isArray(parsed.orderby) ? parsed.orderby.join(",") : parsed.orderby;
} }
if (parsed.inlinecount) {
params.$inlinecount = parsed.inlinecount;
}
return params; return params;
} }
+9 -2
View File
@@ -16,6 +16,11 @@ const booleanFromEnv = z
return ["1", "true", "yes", "on"].includes(value.toLowerCase()); return ["1", "true", "yes", "on"].includes(value.toLowerCase());
}); });
// Service Layer returns only 20 rows per page unless the client asks for more via
// "Prefer: odata.maxpagesize". 500 keeps responses reasonably small while cutting the
// number of Service Layer calls in /all roughly 25 times (2231 records: 5 calls, not 112).
export const DEFAULT_PAGE_SIZE = 500;
export const SapB1ConfigSchema = z.object({ export const SapB1ConfigSchema = z.object({
baseUrl: z.string().url(), baseUrl: z.string().url(),
companyDB: z.string().min(1), companyDB: z.string().min(1),
@@ -25,7 +30,8 @@ export const SapB1ConfigSchema = z.object({
timeout: z.number().int().positive().default(30_000), timeout: z.number().int().positive().default(30_000),
rejectUnauthorized: z.boolean().default(true), rejectUnauthorized: z.boolean().default(true),
retryCount: z.number().int().min(0).default(2), retryCount: z.number().int().min(0).default(2),
retryDelayMs: z.number().int().min(0).default(250) retryDelayMs: z.number().int().min(0).default(250),
pageSize: z.number().int().positive().optional()
}); });
export type SapB1Config = z.infer<typeof SapB1ConfigSchema>; export type SapB1Config = z.infer<typeof SapB1ConfigSchema>;
@@ -42,6 +48,7 @@ export function loadSapB1ConfigFromEnv(env: NodeJS.ProcessEnv = process.env): Sa
timeout: env.SAP_B1_TIMEOUT_MS ? Number(env.SAP_B1_TIMEOUT_MS) : undefined, timeout: env.SAP_B1_TIMEOUT_MS ? Number(env.SAP_B1_TIMEOUT_MS) : undefined,
rejectUnauthorized, rejectUnauthorized,
retryCount: env.SAP_B1_RETRY_COUNT ? Number(env.SAP_B1_RETRY_COUNT) : undefined, retryCount: env.SAP_B1_RETRY_COUNT ? Number(env.SAP_B1_RETRY_COUNT) : undefined,
retryDelayMs: env.SAP_B1_RETRY_DELAY_MS ? Number(env.SAP_B1_RETRY_DELAY_MS) : undefined retryDelayMs: env.SAP_B1_RETRY_DELAY_MS ? Number(env.SAP_B1_RETRY_DELAY_MS) : undefined,
pageSize: env.SAP_B1_PAGE_SIZE ? Number(env.SAP_B1_PAGE_SIZE) : undefined
}); });
} }
+95 -3
View File
@@ -183,6 +183,8 @@ function parseODataQuery(req: Request): ODataQuery {
const top = req.query.$top ?? req.query.top; const top = req.query.$top ?? req.query.top;
const skip = req.query.$skip ?? req.query.skip; const skip = req.query.$skip ?? req.query.skip;
const orderby = req.query.$orderby ?? req.query.orderby; const orderby = req.query.$orderby ?? req.query.orderby;
const inlinecount = req.query.$inlinecount ?? req.query.inlinecount;
const count = req.query.$count ?? req.query.count;
if (typeof select === "string" && select.trim()) { if (typeof select === "string" && select.trim()) {
query.select = select.split(",").map((item) => item.trim()).filter(Boolean); query.select = select.split(",").map((item) => item.trim()).filter(Boolean);
@@ -204,6 +206,12 @@ function parseODataQuery(req: Request): ODataQuery {
query.orderby = orderby; query.orderby = orderby;
} }
// Service Layer v1 speaks OData v3 ($inlinecount=allpages). $count=true is the
// OData v4 spelling, accepted as an alias so v4 clients get the count as well.
if (inlinecount === "allpages" || count === "true") {
query.inlinecount = "allpages";
}
return query; return query;
} }
@@ -259,8 +267,10 @@ function serviceMetadata() {
const ENTITY_SET_PATTERN = /^[A-Za-z0-9_.]+$/; const ENTITY_SET_PATTERN = /^[A-Za-z0-9_.]+$/;
function requireEntitySet(req: Request): string { function requireEntitySet(req: Request): string {
const entitySet = req.params.entitySet; return validateEntitySet(req.params.entitySet);
}
function validateEntitySet(entitySet: string | undefined = ""): string {
if (!ENTITY_SET_PATTERN.test(entitySet)) { if (!ENTITY_SET_PATTERN.test(entitySet)) {
throw new Error(`Invalid entity set name: ${entitySet}`); throw new Error(`Invalid entity set name: ${entitySet}`);
} }
@@ -268,6 +278,21 @@ function requireEntitySet(req: Request): string {
return entitySet; return entitySet;
} }
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Express 4 string paths treat "$" as a regex anchor, so the $count routes are
// RegExp routes. "%24" covers clients that percent-encode the dollar sign.
function countRoute(basePattern: string): RegExp {
return new RegExp(`^${basePattern}/(?:\\$|%24)count/?$`);
}
function countFilter(req: Request): string | undefined {
const filter = req.query.$filter ?? req.query.filter;
return typeof filter === "string" && filter.trim() ? filter : undefined;
}
function formatEntityKey(req: Request): string { function formatEntityKey(req: Request): string {
const raw = req.params.id; const raw = req.params.id;
@@ -332,6 +357,16 @@ function addResourceEndpoints(prefix = "") {
}) })
); );
// Must be registered before /:id, which would otherwise read "$count" as a key.
app.get(
countRoute(`${escapeRegExp(prefix)}/api/entities/(${ENTITY_SET_PATTERN.source.slice(1, -1)})`),
asyncHandler(async (req, res) => {
const entitySet = validateEntitySet(req.params[0]);
const count = await withSap((sap) => sap.client.count(entitySet, countFilter(req)));
res.json({ count });
})
);
app.get( app.get(
`${prefix}/api/entities/:entitySet/:id`, `${prefix}/api/entities/:entitySet/:id`,
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
@@ -387,6 +422,14 @@ function addResourceEndpoints(prefix = "") {
}) })
); );
app.get(
countRoute(escapeRegExp(base)),
asyncHandler(async (req, res) => {
const count = await withSap((sap) => sap.client.count(route.sapEntitySet, countFilter(req)));
res.json({ count });
})
);
app.get( app.get(
`${base}/:id`, `${base}/:id`,
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
@@ -483,10 +526,39 @@ function odataParameters() {
{ name: "$filter", in: "query", required: false, schema: { type: "string" }, description: "OData filter expression." }, { name: "$filter", in: "query", required: false, schema: { type: "string" }, description: "OData filter expression." },
{ name: "$top", in: "query", required: false, schema: { type: "integer", minimum: 1 }, description: "Maximum records to return." }, { name: "$top", in: "query", required: false, schema: { type: "integer", minimum: 1 }, description: "Maximum records to return." },
{ name: "$skip", in: "query", required: false, schema: { type: "integer", minimum: 0 }, description: "Records to skip." }, { name: "$skip", in: "query", required: false, schema: { type: "integer", minimum: 0 }, description: "Records to skip." },
{ name: "$orderby", in: "query", required: false, schema: { type: "string" }, description: "OData order by expression." } { name: "$orderby", in: "query", required: false, schema: { type: "string" }, description: "OData order by expression." },
{
name: "$inlinecount",
in: "query",
required: false,
schema: { type: "string", enum: ["allpages"] },
description: "Set to allpages to get the total number of matching records in odata.count."
},
{
name: "$count",
in: "query",
required: false,
schema: { type: "string", enum: ["true"] },
description: "OData v4 alias for $inlinecount=allpages; the count is returned in odata.count."
}
]; ];
} }
function countParameters() {
return [
{ name: "$filter", in: "query", required: false, schema: { type: "string" }, description: "OData filter expression." }
];
}
function countResponses() {
return {
"200": {
description: "Number of matching records",
content: { "application/json": { example: { count: 2231 } } }
}
};
}
function jsonBody(example: Record<string, unknown>) { function jsonBody(example: Record<string, unknown>) {
return { return {
required: true, required: true,
@@ -627,6 +699,15 @@ function openApiDocument(basePath = "") {
} }
} }
}, },
"/api/entities/{entitySet}/$count": {
get: {
tags: ["Entities"],
summary: "Count records of any entity set",
description: "Maps to SAP Service Layer GET /b1s/v1/{entitySet}/$count. One Service Layer call regardless of the record count.",
parameters: [...securityParameters(), entitySetParameter(), ...countParameters()],
responses: countResponses()
}
},
"/api/entities/{entitySet}/{id}": { "/api/entities/{entitySet}/{id}": {
get: { get: {
tags: ["Entities"], tags: ["Entities"],
@@ -685,7 +766,8 @@ function openApiDocument(basePath = "") {
get: { get: {
tags: [route.tag], tags: [route.tag],
summary: `Load all ${route.sapEntitySet} pages`, summary: `Load all ${route.sapEntitySet} pages`,
description: "Follows odata.nextLink/@odata.nextLink until all pages are loaded. Use carefully for large datasets.", description:
"Follows odata.nextLink/@odata.nextLink until all pages are loaded, asking Service Layer for SAP_B1_PAGE_SIZE records per page (default 500). Use carefully for large datasets; for a record count use /$count.",
parameters: [...securityParameters(), ...odataParameters()], parameters: [...securityParameters(), ...odataParameters()],
responses: { responses: {
"200": { description: "Object with value array containing all loaded records" } "200": { description: "Object with value array containing all loaded records" }
@@ -693,6 +775,16 @@ function openApiDocument(basePath = "") {
} }
}; };
paths[`${base}/$count`] = {
get: {
tags: [route.tag],
summary: `Count ${route.sapEntitySet} records`,
description: `Maps to SAP Service Layer GET /b1s/v1/${route.sapEntitySet}/$count. One Service Layer call regardless of the record count.`,
parameters: [...securityParameters(), ...countParameters()],
responses: countResponses()
}
};
const itemOperations: Record<string, unknown> = { const itemOperations: Record<string, unknown> = {
get: { get: {
tags: [route.tag], tags: [route.tag],
+7 -1
View File
@@ -6,10 +6,13 @@ export interface ODataQuery {
top?: number; top?: number;
skip?: number; skip?: number;
orderby?: string | string[]; orderby?: string | string[];
inlinecount?: "allpages";
} }
export interface ODataResponse<T> { export interface ODataResponse<T> {
value: T[]; value: T[];
"odata.count"?: string | number;
"@odata.count"?: number;
"odata.metadata"?: string; "odata.metadata"?: string;
"odata.nextLink"?: string; "odata.nextLink"?: string;
"@odata.context"?: string; "@odata.context"?: string;
@@ -21,12 +24,15 @@ export const ODataQuerySchema = z.object({
filter: z.string().min(1).optional(), filter: z.string().min(1).optional(),
top: z.number().int().positive().optional(), top: z.number().int().positive().optional(),
skip: z.number().int().min(0).optional(), skip: z.number().int().min(0).optional(),
orderby: z.union([z.string().min(1), z.array(z.string().min(1))]).optional() orderby: z.union([z.string().min(1), z.array(z.string().min(1))]).optional(),
inlinecount: z.literal("allpages").optional()
}); });
export const ODataResponseSchema = <T extends z.ZodTypeAny>(itemSchema: T) => export const ODataResponseSchema = <T extends z.ZodTypeAny>(itemSchema: T) =>
z.object({ z.object({
value: z.array(itemSchema), value: z.array(itemSchema),
"odata.count": z.union([z.string(), z.number()]).optional(),
"@odata.count": z.number().optional(),
"odata.metadata": z.string().optional(), "odata.metadata": z.string().optional(),
"odata.nextLink": z.string().optional(), "odata.nextLink": z.string().optional(),
"@odata.context": z.string().optional(), "@odata.context": z.string().optional(),
+44
View File
@@ -151,4 +151,48 @@ describe("SapB1Client", () => {
expect(all).toEqual([{ ItemCode: "A1" }, { ItemCode: "A2" }]); expect(all).toEqual([{ ItemCode: "A1" }, { ItemCode: "A2" }]);
expect(requestedUrls).toEqual(["Items", "Items?$skip=20"]); expect(requestedUrls).toEqual(["Items", "Items?$skip=20"]);
}); });
it("asks Service Layer for larger pages when loading all records", async () => {
const preferHeaders: unknown[] = [];
const http = axios.create({
adapter: async (requestConfig) => {
if (requestConfig.url === "/Login") {
return {
...response({ SessionId: "abc123", SessionTimeout: 30 }, requestConfig),
headers: { "set-cookie": ["B1SESSION=abc123; Path=/b1s/v1"] }
};
}
preferHeaders.push(requestConfig.headers?.Prefer);
return response({ value: [] }, requestConfig);
}
});
const client = new SapB1Client({ ...config, pageSize: 250 }, { http });
await client.getAll("BusinessPartners");
expect(preferHeaders).toEqual(["odata.maxpagesize=250"]);
});
it("reads the record count from the $count endpoint", async () => {
const requests: Array<{ url: unknown; params: unknown }> = [];
const http = axios.create({
adapter: async (requestConfig) => {
if (requestConfig.url === "/Login") {
return {
...response({ SessionId: "abc123", SessionTimeout: 30 }, requestConfig),
headers: { "set-cookie": ["B1SESSION=abc123; Path=/b1s/v1"] }
};
}
requests.push({ url: requestConfig.url, params: requestConfig.params });
return response("2231", requestConfig);
}
});
const client = new SapB1Client(config, { http });
await expect(client.count("BusinessPartners", "CardType eq 'cCustomer'")).resolves.toBe(2231);
expect(requests).toEqual([{ url: "BusinessPartners/$count", params: { $filter: "CardType eq 'cCustomer'" } }]);
});
}); });
+4
View File
@@ -20,6 +20,10 @@ describe("OData helpers", () => {
}); });
}); });
it("passes $inlinecount through to Service Layer", () => {
expect(buildODataParams({ top: 1, inlinecount: "allpages" })).toEqual({ $top: 1, $inlinecount: "allpages" });
});
it("supports old and new nextLink field names", () => { it("supports old and new nextLink field names", () => {
expect(extractNextLink({ "@odata.nextLink": "Items?$skip=20" })).toBe("Items?$skip=20"); expect(extractNextLink({ "@odata.nextLink": "Items?$skip=20" })).toBe("Items?$skip=20");
expect(extractNextLink({ "odata.nextLink": "Items?$skip=40" })).toBe("Items?$skip=40"); expect(extractNextLink({ "odata.nextLink": "Items?$skip=40" })).toBe("Items?$skip=40");