budibase/packages/server/middleware/controllers/record.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-04-09 11:13:19 +02:00
const couchdb = require("../../db")
const {
events,
schemaValidator
} = require("../../../common");
2020-04-07 16:12:08 +02:00
2020-04-09 17:53:48 +02:00
exports.save = async function(ctx) {
const db = new CouchDB(ctx.params.instanceId);
const record = ctx.request.body;
2020-04-08 17:57:27 +02:00
// validation with ajv
const model = await db.get(ctx.params.modelId);
const validate = schemaValidator.compile({
properties: model.schema
});
const valid = validate(record);
2020-04-09 11:13:19 +02:00
if (!valid) {
ctx.status = 400;
ctx.body = {
status: 400,
errors: validate.errors
};
return;
2020-04-09 11:13:19 +02:00
}
const existingRecord = record._id && await db.get(record._id);
if (existingRecord) {
const response = await db.put({ ...record, _id: existingRecord._id });
ctx.body = {
message: "Record updated successfully.",
status: 200,
record: response
}
return;
2020-04-09 11:13:19 +02:00
}
const response = await db.post({
modelId: ctx.params.modelId,
type: "record",
...record
})
// await ctx.publish(events.recordApi.save.onRecordCreated, {
// record: record,
// })
ctx.body = {
message: "Record created successfully.",
status: 200,
record: response
};
2020-04-09 11:13:19 +02:00
}
exports.fetch = async function(ctx) {
const db = new CouchDB(ctx.params.instanceId)
const response = await db.query(
`database/${ctx.params.viewName}`,
2020-04-09 17:42:55 +02:00
{
include_docs: true
2020-04-09 17:42:55 +02:00
}
)
ctx.body = response.rows.map(row => row.doc);
2020-04-09 11:13:19 +02:00
}
2020-04-09 17:53:48 +02:00
exports.find = async function(ctx) {
2020-04-09 11:13:19 +02:00
const db = couchdb.db.use(ctx.params.databaseId)
const record = await db.get(ctx.params.recordId);
2020-04-09 11:13:19 +02:00
ctx.body = record;
ctx.status = 200;
2020-04-09 11:13:19 +02:00
}
2020-04-09 17:53:48 +02:00
exports.destroy = async function(ctx) {
const databaseId = ctx.params.instanceId;
const db = new CouchDB(databaseId)
ctx.body = await db.destroy(ctx.params.recordId, ctx.params.revId);
2020-04-09 17:53:48 +02:00
};