UNPKG

@opengis/fastify-table

Version:

core-plugins

50 lines (39 loc) 1.96 kB
import getPG from './getPG.js'; const data = {}; // decorator export default async function getMeta(opt, nocache) { const pg = opt?.pg || getPG({ name: 'client' }); if (!pg) return { error: 'pg connection not established', status: 400 }; const table1 = opt?.table || opt; const table = pg.pk[table1] ? table1 : table1?.replace?.(/"/g, ''); if (pg?.options?.database && data[pg.options.database]?.[table] && !nocache) return data[pg.options.database][table]; if (!pg?.tlist?.includes(table)) { return { error: `${table} - not found`, status: 400 }; } const { fields = [] } = await pg.query(`select * from ${table} limit 0`); const pks1 = await pg.query(`SELECT json_object_agg(c.conrelid::regclass, a.attname) as pks1 FROM pg_constraint c left join pg_attribute a on c.conrelid=a.attrelid and a.attnum = c.conkey[1] WHERE c.contype='p'::"char" and c.conrelid::regclass = $1::regclass`, [table]).then(el => el.rows[0].pks1 || {}); const pk = table.startsWith('public.') ? (pks1[table.replace('public.', '')] || pks1[table.replace('public.', '')]) : (pks1[table] || pks1[table]); const geomAttr = fields.find((el) => pg.pgType?.[el.dataTypeID] === 'geometry')?.name; // change geometry text to geometry code const dbColumns = await pg.query(`select json_object_agg( attname, json_build_object( 'title', pg_catalog.col_description(attrelid,attnum) /*,'type', atttypid::regtype */ ) ) from pg_catalog.pg_attribute a where attrelid=$1::regclass and attnum>0`, [table]).then(el => el.rows?.[0]?.json_object_agg || {}); fields.forEach(el => Object.assign(el, { ...dbColumns[el.name] || {} })); const res = { pk, columns: fields, geom: geomAttr, view: pg.relkinds?.[table] === 'v', }; if (!data[pg.options.database]) { data[pg.options.database] = {}; } data[pg.options.database][table] = res; return res; }