diff --git a/.env.example b/.env.example index 64893f5..e61048e 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,8 @@ SAP_B1_TIMEOUT_MS=30000 SAP_B1_REJECT_UNAUTHORIZED=true SAP_B1_RETRY_COUNT=2 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 # musi poslat hlavicku X-Api-Key se stejnou hodnotou. diff --git a/README.md b/README.md index 815f3ce..1ea85ce 100644 --- a/README.md +++ b/README.md @@ -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/entities` (seznam všech entity setů) - `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 /api/` - `GET /api//all` +- `GET /api//$count` - `GET /api//{id}` - `POST /api/` - `PATCH /api//{id}` @@ -48,11 +50,14 @@ SAP_B1_TIMEOUT_MS=30000 SAP_B1_REJECT_UNAUTHORIZED=true SAP_B1_RETRY_COUNT=2 SAP_B1_RETRY_DELAY_MS=250 +SAP_B1_PAGE_SIZE=500 API_KEY= ``` `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 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: diff --git a/documentation/sap-business-one-service-layer.md b/documentation/sap-business-one-service-layer.md index 3ae9227..c94610a 100644 --- a/documentation/sap-business-one-service-layer.md +++ b/documentation/sap-business-one-service-layer.md @@ -45,6 +45,19 @@ Bezpečnostní pravidla: (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 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=` + (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//$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 diff --git a/src/client/SapB1Client.ts b/src/client/SapB1Client.ts index a00909c..1f6e446 100644 --- a/src/client/SapB1Client.ts +++ b/src/client/SapB1Client.ts @@ -3,7 +3,7 @@ import https from "node:https"; import axios, { AxiosInstance, AxiosRequestConfig, Method } from "axios"; import { z } from "zod"; 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 { ODataQuery, ODataResponse } from "../types/odata"; import { buildODataParams, extractNextLink } from "./odata"; @@ -50,6 +50,14 @@ export class SapB1Client { return this.request("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 { + return this.request("GET", `${path}/$count`, undefined, { + params: buildODataParams(filter ? { filter } : {}), + schema: z.coerce.number().int().min(0) + }); + } + public post(path: string, data?: unknown, schema?: z.ZodType): Promise { return this.request("POST", path, data, { schema }); } @@ -68,7 +76,10 @@ export class SapB1Client { let nextQuery: ODataQuery | undefined = query; while (nextPath) { - const response: ODataResponse = await this.get>(nextPath, nextQuery); + const response: ODataResponse = await this.request>("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; items.push(...value); const nextLink: string | undefined = extractNextLink(response); diff --git a/src/client/odata.ts b/src/client/odata.ts index 6be8540..0d075ce 100644 --- a/src/client/odata.ts +++ b/src/client/odata.ts @@ -24,6 +24,10 @@ export function buildODataParams(query: ODataQuery = {}): Record; @@ -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, rejectUnauthorized, 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 }); } diff --git a/src/index.ts b/src/index.ts index 257e24a..8711872 100644 --- a/src/index.ts +++ b/src/index.ts @@ -183,6 +183,8 @@ function parseODataQuery(req: Request): ODataQuery { const top = req.query.$top ?? req.query.top; const skip = req.query.$skip ?? req.query.skip; 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()) { query.select = select.split(",").map((item) => item.trim()).filter(Boolean); @@ -204,6 +206,12 @@ function parseODataQuery(req: Request): ODataQuery { 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; } @@ -259,8 +267,10 @@ function serviceMetadata() { const ENTITY_SET_PATTERN = /^[A-Za-z0-9_.]+$/; 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)) { throw new Error(`Invalid entity set name: ${entitySet}`); } @@ -268,6 +278,21 @@ function requireEntitySet(req: Request): string { 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 { 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( `${prefix}/api/entities/:entitySet/:id`, 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( `${base}/:id`, asyncHandler(async (req, res) => { @@ -483,10 +526,39 @@ function odataParameters() { { 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: "$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) { return { 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}": { get: { tags: ["Entities"], @@ -685,7 +766,8 @@ function openApiDocument(basePath = "") { get: { tags: [route.tag], 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()], responses: { "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 = { get: { tags: [route.tag], diff --git a/src/types/odata.ts b/src/types/odata.ts index 0bbe353..69a6bbb 100644 --- a/src/types/odata.ts +++ b/src/types/odata.ts @@ -6,10 +6,13 @@ export interface ODataQuery { top?: number; skip?: number; orderby?: string | string[]; + inlinecount?: "allpages"; } export interface ODataResponse { value: T[]; + "odata.count"?: string | number; + "@odata.count"?: number; "odata.metadata"?: string; "odata.nextLink"?: string; "@odata.context"?: string; @@ -21,12 +24,15 @@ export const ODataQuerySchema = z.object({ filter: z.string().min(1).optional(), top: z.number().int().positive().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 = (itemSchema: T) => z.object({ value: z.array(itemSchema), + "odata.count": z.union([z.string(), z.number()]).optional(), + "@odata.count": z.number().optional(), "odata.metadata": z.string().optional(), "odata.nextLink": z.string().optional(), "@odata.context": z.string().optional(), diff --git a/tests/client.test.ts b/tests/client.test.ts index 0efe2f1..d13b784 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -151,4 +151,48 @@ describe("SapB1Client", () => { expect(all).toEqual([{ ItemCode: "A1" }, { ItemCode: "A2" }]); 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'" } }]); + }); }); diff --git a/tests/odata.test.ts b/tests/odata.test.ts index 4925f79..9d80aa8 100644 --- a/tests/odata.test.ts +++ b/tests/odata.test.ts @@ -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", () => { expect(extractNextLink({ "@odata.nextLink": "Items?$skip=20" })).toBe("Items?$skip=20"); expect(extractNextLink({ "odata.nextLink": "Items?$skip=40" })).toBe("Items?$skip=40");