UNPKG

cap-cds-mongoose

Version:

MongoDB (Mongoose) persistence adapter & deployer for SAP CAP (works like @cap-js/hana / @cap-js/sqlite)

69 lines (59 loc) 2.3 kB
// lib/deployer.js const fs = require("fs"); const path = require("path"); const csv = require("csv-parser"); const cds = require("@sap/cds"); const { connect } = require("./connection"); const { getModel, modelName } = require("./mapper"); /** * Entry for cd deploy --to mongoose * cds will call the function exported by the deployer plugin */ async function deploy(csn, options = {}) { // csn might be either raw or cds.model const model = csn.definitions ? csn : cds.model; // attempt await connect(process.env.MONGO_URL); const definitions = model.definitions || {}; // iterate entities for (const name of Object.keys(definitions)) { const def = definitions[name]; if (!def || def.kind !== "entity") continue; console.log(`[mongoose-cap-amo] Ensuring collection for ${name}`); const m = getModel(model, def); // will create mongoose model // Optionally clear/ensure indices -- keep minimal try { await m.createCollection(); } catch (e) { // collection may already exist; ignore } // look for seed CSV in db/data/<namespace-entity>.csv or db/data/<entity>.csv const shortName = modelName(name); const csvCandidates = [ path.join(process.cwd(), "db", "data", `${shortName}.csv`), path.join(process.cwd(), "db", "data", `${name.replace(/\./g, "-")}.csv`), path.join(process.cwd(), "db", "data", `${name.split(".").pop()}.csv`) ]; for (const csvFile of csvCandidates) { if (fs.existsSync(csvFile)) { console.log(`[mongoose-cap-amo] Importing records from ${csvFile}`); const rows = []; await new Promise((resolve) => { fs.createReadStream(csvFile) .pipe(csv()) .on("data", (data) => rows.push(data)) .on("end", resolve); }); if (rows.length) { // convert simple types? For now insert strings and let Mongoose cast // wipe existing await m.deleteMany({}); await m.insertMany(rows); console.log(`[mongoose-cap-amo] Imported ${rows.length} rows into ${name}`); } break; } } } console.log("[mongoose-cap-amo] deploy complete"); } module.exports = { deploy };