import { ensureArray } from "./match/utils.js"; const arrayParams = ["sort", "where", "only", "without"]; export function createQuery(fetcher, opts = {}) { const queryParams = {}; for (const key of Object.keys(opts.initialParams || {})) { queryParams[key] = arrayParams.includes(key) ? ensureArray(opts.initialParams[key]) : opts.initialParams[key]; } const $set = (key, fn = (v) => v) => { return (...values) => { queryParams[key] = fn(...values); return query; }; }; const resolveResult = (result) => { if (opts.legacy) { if (result?.surround) { return result.surround; } if (!result) { return result; } if (result?.dirConfig) { result.result = { _path: result.dirConfig?._path, ...result.result, _dir: result.dirConfig }; } return result?._path || Array.isArray(result) || !Object.prototype.hasOwnProperty.call(result, "result") ? result : result?.result; } return result; }; const query = { params: () => ({ ...queryParams, ...queryParams.where ? { where: [...ensureArray(queryParams.where)] } : {}, ...queryParams.sort ? { sort: [...ensureArray(queryParams.sort)] } : {} }), only: $set("only", ensureArray), without: $set("without", ensureArray), where: $set("where", (q) => [...ensureArray(queryParams.where), ...ensureArray(q)]), sort: $set("sort", (sort) => [...ensureArray(queryParams.sort), ...ensureArray(sort)]), limit: $set("limit", (v) => parseInt(String(v), 10)), skip: $set("skip", (v) => parseInt(String(v), 10)), // find find: () => fetcher(query).then(resolveResult), findOne: () => fetcher($set("first")(true)).then(resolveResult), count: () => fetcher($set("count")(true)).then(resolveResult), // locale locale: (_locale) => query.where({ _locale }), withSurround: $set("surround", (surroundQuery, options) => ({ query: surroundQuery, ...options })), withDirConfig: () => $set("dirConfig")(true) }; if (opts.legacy) { query.findSurround = (surroundQuery, options) => { return query.withSurround(surroundQuery, options).find().then(resolveResult); }; return query; } return query; }