Files
dougal-software/lib/www/server/lib/db/sequence/get.js
2025-08-22 16:01:20 +02:00

110 lines
2.9 KiB
JavaScript

const { setSurvey } = require('../connection');
async function getSummary (projectId, sequence, opts = {}) {
const client = await setSurvey(projectId);
const text = `
SELECT *
FROM sequences_summary
WHERE sequence = $1;
`;
const res = await client.query(text, [sequence]);
client.release();
return res.rows[0];
}
async function getPoints (projectId, sequence, opts = {}) {
const offset = Math.abs(opts.offset) || Math.abs((opts.page-1)*opts.itemsPerPage) || 0;
const limit = Math.abs(opts.limit) || Math.abs(Number(opts.itemsPerPage)) || null;
const client = await setSurvey(projectId);
const restriction = sequence
? "sequence = $3"
: "TRUE OR $3";
const text = `
SELECT line, point, sequence, st_x(ST_Transform(geometry, 4326)) longitude, st_y(ST_Transform(geometry, 4326)) latitude
FROM final_shots
WHERE ${restriction}
ORDER BY sequence, point
OFFSET $1
LIMIT $2;
`;
try {
const res = await client.query({text, values: [offset, limit, sequence], rowMode: 'array'});
return res.rows;
} catch (err) {
console.error(err);
// throw { status: 500, message: "Internal error" };
} finally {
client.release();
}
}
async function get (projectId, sequence, opts = {}) {
if (opts.summary) {
return await getSummary(projectId, sequence, opts);
}
if (opts.type == 4) {
// The user is request that we send just the bare details:
// sequence, sailline, line, longitude, latitude.
//
// This will probably be a binary data request (though doesn't
// need to).
return await getPoints(projectId, sequence, opts);
}
const client = await setSurvey(projectId);
const sortFields = [
"sequence", "sailline", "line", "point", "tstamp"
];
const sortKey = opts.sortBy && sortFields.includes(opts.sortBy) && opts.sortBy || "tstamp";
const sortDir = opts.sortDesc == "false" ? "ASC" : "DESC";
const offset = Math.abs(opts.offset) || Math.abs((opts.page-1)*opts.itemsPerPage) || 0;
const limit = Math.abs(opts.limit) || Math.abs(Number(opts.itemsPerPage)) || null;
const restriction = sequence
? "sequence = $3"
: "TRUE OR $3";
const text = `
SELECT
sequence, sailline, line, point, tstamp,
objRefRaw, objRefFinal,
geometryPreplot::json,
geometryRaw::json,
geometryFinal::json,
errorRaw::json,
errorFinal::json,
jsonb_path_query(meta::jsonb, $4) as meta
FROM sequences_detail
WHERE ${restriction}
ORDER BY ${sortKey} ${sortDir}
OFFSET $1
LIMIT $2;
`;
const values = [offset, limit, sequence, opts.path || "$"];
const res = await client.query(text, values);
client.release();
if (opts.project) {
const tokens = opts.project.split(/\s*[,;:\s]\s*/).filter(e => e.length);
const project = tokens.map(i => i.replace(/^([^.]+)\..*$/, "$1"));
return res.rows.map( r =>
Object.fromEntries(Object.entries(r).filter(entry => project.includes(entry[0])))
);
} else {
return res.rows;
}
}
module.exports = get;