stackpress
Version:
Incept is a content management framework.
51 lines (50 loc) • 2.06 kB
JavaScript
export default function AdminExportPageFactory(model) {
return async function AdminSearchPage(req, res, ctx) {
if (res.body || (res.code && res.code !== 200)) {
return;
}
let { q, filter, span, sort } = req.data();
const response = await ctx.resolve(`${model.dash}-search`, { q, filter, span, sort, take: 0 });
if (response.code === 200 && response.results) {
const head = [];
const body = [];
const relations = model.relations.map(column => column.name);
for (const data of response.results) {
for (const key in data) {
const includes = head.find(head => head[0] === '' && head[1] === key);
if (!includes && !relations.includes(key)) {
head.push(['', key]);
}
}
for (const relation of relations) {
if (!data[relation])
continue;
for (const key in data[relation]) {
const includes = head.find(head => head[0] === relation && head[1] === key);
if (!includes) {
head.push([relation, key]);
}
}
}
const row = [];
for (const [relation, key] of head) {
if (relation === '') {
row.push(data[key]);
}
else {
const column = data[relation];
row.push(column?.[key]);
}
}
body.push(row);
}
const csv = [
head.map(entry => entry[1]),
...body
].map(row => row.join(',')).join('\n');
res.headers.set('Content-Disposition', `attachment; filename=${model.dash}-${Date.now()}.csv`);
res.setBody('text/csv', csv);
}
};
}
;