/
tangy-form-service.ts
85 lines (70 loc) · 2.28 KB
/
tangy-form-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import PouchDB from 'pouchdb';
import {TangyFormResponseModel} from 'tangy-form/tangy-form-response-model.js'
import axios from 'axios'
// A dummy function so TS does not complain about our use of emit in our pouchdb queries.
const emit = (key, value) => {
return true;
}
export class TangyFormService {
db:any;
databaseName: String;
constructor(props) {
this.databaseName = 'tangy-forms'
Object.assign(this, props)
this.db = new PouchDB(this.databaseName, {auto_compaction: true, revs_limit: 1})
}
async initialize() {
console.warn('TangyFormService.initialize is deprecated and no longer needed. Please remove its usage.')
}
async getFormMarkup(formId) {
const formInfo = await this.getFormInfo(formId)
const formMarkup:any = (await axios.get(formInfo.src)).data
return formMarkup
}
async getFormInfo(formId) {
const formsInfo:any = await this.getFormsInfo()
return formsInfo.find(formInfo => formInfo.id === formId)
}
async getFormsInfo() {
const formsInfo:any = (await axios.get('./assets/forms.json')).data
return formsInfo
}
async saveForm(formDoc) {
let r
if (!formDoc._id) {
r = await this.db.post(formDoc)
}
else {
r = await this.db.put(formDoc)
}
return await this.db.get(r.id)
}
// Would be nice if this was queue based so if two saves get called at the same time, the differentials are sequentials updated
// into the database. Using a getter and setter for property fields, this would be one way to queue.
async saveResponse(responseDoc) {
let r
if (!responseDoc._id) {
r = await this.db.post(responseDoc)
}
else {
r = await this.db.put(responseDoc)
}
return await this.db.get(r.id)
}
async getResponse(responseId) {
try {
let doc = await this.db.get(responseId)
return doc
} catch (e) {
return false
}
}
async getResponsesByFormId(formId) {
let r = await this.db.query('tangy-form/responsesByFormId', { key: formId, include_docs: true })
return r.rows.map((row) => new TangyFormResponseModel(row.doc))
}
async getResponsesByLocationId(locationId) {
let r = await this.db.query('tangy-form/responsesByLocationId', { key: locationId, include_docs: true })
return r.rows.map((row) => row.doc)
}
}