@ztl-uwu/nuxt-content
Version:
Write your content inside your Nuxt app
105 lines (104 loc) • 3.4 kB
JavaScript
import { joinURL } from "ufo";
import { apply, ensureArray, sortList, withoutKeys, withKeys, omit } from "./utils.js";
import { createMatch } from "./index.js";
export function createPipelineFetcher(getContentsList) {
const match = createMatch();
const surround = (data, { query, before, after }) => {
const matchQuery = typeof query === "string" ? { _path: query } : query;
const index = data.findIndex((item) => match(item, matchQuery));
before = before ?? 1;
after = after ?? 1;
const slice = new Array(before + after).fill(null, 0);
return index === -1 ? slice : slice.map((_, i) => data[index - before + i + Number(i >= before)] || null);
};
const matchingPipelines = [
// Conditions
(state, params) => {
const filtered = state.result.filter((item) => ensureArray(params.where).every((matchQuery) => match(item, matchQuery)));
return {
...state,
result: filtered,
total: filtered.length
};
},
// Sort data
(state, params) => ensureArray(params.sort).forEach((options) => sortList(state.result, options)),
function fetchSurround(state, params, db) {
if (params.surround) {
let _surround = surround(state.result?.length === 1 ? db : state.result, params.surround);
_surround = apply(withoutKeys(params.without))(_surround);
_surround = apply(withKeys(params.only))(_surround);
state.surround = _surround;
}
return state;
}
];
const transformingPiples = [
// Skip first items
(state, params) => {
if (params.skip) {
return {
...state,
result: state.result.slice(params.skip),
skip: params.skip
};
}
},
// Pick first items
(state, params) => {
if (params.limit) {
return {
...state,
result: state.result.slice(0, params.limit),
limit: params.limit
};
}
},
function fetchDirConfig(state, params, db) {
if (params.dirConfig) {
const path = state.result[0]?._path || params.where?.find((w) => w._path)?._path;
if (typeof path === "string") {
const dirConfig = db.find((item) => item._path === joinURL(path, "_dir"));
if (dirConfig) {
state.dirConfig = { _path: dirConfig._path, ...withoutKeys(["_"])(dirConfig) };
}
}
}
return state;
},
// Remove unwanted fields
(state, params) => ({
...state,
result: apply(withoutKeys(params.without))(state.result)
}),
// Select only wanted fields
(state, params) => ({
...state,
result: apply(withKeys(params.only))(state.result)
})
];
return async (query) => {
const db = await getContentsList();
const params = query.params();
const result1 = {
result: db,
limit: 0,
skip: 0,
total: db.length
};
const matchedData = matchingPipelines.reduce(($data, pipe) => pipe($data, params, db) || $data, result1);
if (params.count) {
return {
result: matchedData.result.length
};
}
const result = transformingPiples.reduce(($data, pipe) => pipe($data, params, db) || $data, matchedData);
if (params.first) {
return {
...omit(["skip", "limit", "total"])(result),
result: result.result[0]
};
}
return result;
};
}