
const { setSurvey } = require('../../../connection');

async function get (projectId, layerName = null, options = {}) {

	const client = await setSurvey(projectId);

	const text = `
		SELECT path, (data - 'type') data
		FROM files f
			INNER JOIN file_data
			USING (hash)
		WHERE data->>'type' = 'map_layer'
			AND data->>'format' = 'geojson'
			AND (data->>'name' = $1
				OR $1 IS NULL);
	`;

	const values = [ layerName ];

	const res = await client.query(text, values);
	client.release();

	if (res.rows && res.rows.length) {
		return res.rows.map(row => ({...row.data, path: row.path}));
	} else {
		throw {status: 404, message: "Not found"};
	}
}

module.exports = get;
