Tuesday, December 24, 2019

The example of calling server-side API functions

Here is the simple example of calling server-side API functions that are written in JavaScript. The back-end team used Sequelize ORM package on Node.js. Also, we've created the client-side API that used Axios package to call server-side functions (from controllers).

1) Here is the screen shot of list component, which content we got by calling server-side API:

2) The code snippets:

- The part of code from client API (lines 12 and 24):
export default {
async getDocuments (documentTypeId, moduleId, params) {
let url = '/api/developed-documents'
if (documentTypeId) {
url += `?documentTypeId=${documentTypeId}`
} else if (moduleId) {
url += `?moduleId=${moduleId}`
}
const { data } = await axios.post(url, params)
return data
},
async getDocumentTypes (moduleId) {
let url = '/api/developed-documents/types'
if (moduleId) {
url += `?moduleId=${moduleId}`
}
const { data } = await axios.get(url)
return data
}
}
view raw client_api.js hosted with ❤ by GitHub

- The part of code from .vue list component (lines 4 and 18):
<script>
export default {
async mounted () {
this.documentTypes = await developedDocumentsApi.getDocumentTypes(this.currentModule.id)
await this.refreshDocumentList()
},
methods: {
...mapActions({
navigate: 'developedDocuments/navigate',
setCurrentDocument: 'developedDocuments/setCurrentDocument',
setDrawingsAllowed: 'developedDocuments/setDrawingsAllowed'
}),
async refreshDocumentList () {
try {
const currentDocumentId = this.selectedDocument ? this.selectedDocument.id : null
this.$refs.table.setBusy(true)
const { rows, count } = await developedDocumentsApi.getDocuments(this.selectedDocumentTypeId, this.currentModule.id, this.params)
this.count = count
this.documents = rows
if (currentDocumentId) {
this.selectedDocument = this.documents.find(x => x.id === currentDocumentId)
if (this.selectedDocument) {
await this.onDocumentSelected(this.selectedDocument)
} else {
this.currentStep = null
this.currentHandler = null
}
} else {
this.selectedDocument = null
this.currentStep = null
this.currentHandler = null
}
} catch (err) {
this.$error('Ошибка получения данных')
} finally {
this.$refs.table.setBusy(false)
}
},
}
</script>
view raw list.vue hosted with ❤ by GitHub

0 comments:

Post a Comment