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

71 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-05-07 11:53:34 +02:00
const CouchDB = require("../../db")
const Ajv = require("ajv")
2020-05-04 18:13:57 +02:00
2020-05-07 11:53:34 +02:00
const ajv = new Ajv()
2020-04-07 16:12:08 +02:00
2020-04-09 17:53:48 +02:00
exports.save = async function(ctx) {
2020-05-07 11:53:34 +02:00
const db = new CouchDB(ctx.params.instanceId)
const record = ctx.request.body
2020-04-08 17:57:27 +02:00
// validation with ajv
2020-04-22 17:35:20 +02:00
const model = await db.get(record.modelId)
2020-05-04 18:13:57 +02:00
const validate = ajv.compile({
2020-05-07 11:53:34 +02:00
properties: model.schema,
})
2020-04-22 17:35:20 +02:00
const valid = validate(record)
2020-04-09 11:13:19 +02:00
if (!valid) {
2020-04-22 17:35:20 +02:00
ctx.status = 400
ctx.body = {
status: 400,
2020-05-07 11:53:34 +02:00
errors: validate.errors,
}
return
2020-04-09 11:13:19 +02:00
}
2020-05-07 11:53:34 +02:00
const existingRecord = record._id && (await db.get(record._id))
if (existingRecord) {
2020-05-07 11:53:34 +02:00
const response = await db.put({ ...record, _id: existingRecord._id })
ctx.body = {
2020-04-24 19:02:51 +02:00
message: `${model.name} updated successfully.`,
status: 200,
2020-04-24 19:02:51 +02:00
record: {
...record,
2020-05-07 11:53:34 +02:00
...response,
},
}
2020-04-22 17:35:20 +02:00
return
2020-04-09 11:13:19 +02:00
}
2020-04-22 17:35:20 +02:00
record.type = "record"
2020-04-23 15:42:26 +02:00
const response = await db.post(record)
2020-04-22 17:35:20 +02:00
record._rev = response.rev
// await ctx.publish(events.recordApi.save.onRecordCreated, {
// record: record,
// })
2020-04-22 17:35:20 +02:00
ctx.body = record
ctx.status = 200
2020-04-24 19:02:51 +02:00
ctx.message = `${model.name} created successfully`
2020-04-09 11:13:19 +02:00
}
exports.fetch = async function(ctx) {
2020-04-24 18:28:32 +02:00
const db = new CouchDB(ctx.params.instanceId)
2020-05-07 11:53:34 +02:00
const response = await db.query(`database/${ctx.params.viewName}`, {
include_docs: true,
})
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-24 18:28:32 +02:00
const db = new CouchDB(ctx.params.instanceId)
2020-04-22 17:35:20 +02:00
ctx.body = await db.get(ctx.params.recordId)
2020-04-09 11:13:19 +02:00
}
2020-04-09 17:53:48 +02:00
exports.destroy = async function(ctx) {
2020-05-07 11:53:34 +02:00
const databaseId = ctx.params.instanceId
2020-04-24 18:28:32 +02:00
const db = new CouchDB(databaseId)
2020-05-07 11:53:34 +02:00
ctx.body = await db.remove(ctx.params.recordId, ctx.params.revId)
}