1
0
Fork 0
mirror of synced 2024-07-04 14:01:27 +12:00
budibase/packages/server/middleware/controllers/record.js

81 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-04-09 21:13:19 +12:00
const couchdb = require("../../db")
const {
events,
schemaValidator
} = require("@budibase/common")
2020-04-08 02:12:08 +12:00
2020-04-10 03:53:48 +12:00
exports.save = async function(ctx) {
const db = couchdb.db.use(ctx.params.instanceId);
const record = ctx.request.body;
2020-04-09 03:57:27 +12: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 21:13:19 +12:00
if (!valid) {
ctx.status = 400;
ctx.body = {
status: 400,
errors: validate.errors
};
return;
2020-04-09 21:13:19 +12:00
}
const existingRecord = record._id && await db.get(record._id);
if (existingRecord) {
const response = await db.insert(record, existingRecord._id)
ctx.body = {
message: "Record updated successfully.",
status: 200,
record: response
}
return;
2020-04-09 21:13:19 +12:00
}
const response = await db.insert({
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 21:13:19 +12:00
}
exports.fetch = async function(ctx) {
const db = couchdb.db.use(ctx.params.instanceId)
const response = await db.view(
"database",
ctx.params.viewName,
2020-04-10 03:42:55 +12:00
{
include_docs: true
2020-04-10 03:42:55 +12:00
}
)
ctx.body = response.rows.map(row => row.doc);
2020-04-09 21:13:19 +12:00
}
2020-04-10 03:53:48 +12:00
exports.find = async function(ctx) {
2020-04-09 21:13:19 +12:00
const db = couchdb.db.use(ctx.params.databaseId)
const record = await db.get(ctx.params.recordId);
2020-04-09 21:13:19 +12:00
ctx.body = record;
ctx.status = 200;
2020-04-09 21:13:19 +12:00
}
2020-04-10 03:53:48 +12:00
exports.destroy = async function(ctx) {
const databaseId = ctx.params.instanceId;
const db = couchdb.db.use(databaseId)
ctx.body = await db.destroy(ctx.params.recordId, ctx.params.revId);
2020-04-10 03:53:48 +12:00
};