1.0.2 • Published 6 years ago
hiep294-apiconnection v1.0.2
Basic API Connection
This module and module 'hiep294-route' are a couple. This module is to use for client side.
Example
Suppose that in app my todo list, a todo has the following fields: _id(created automactically by mongodb), title, isCompleted
Create this todoAPIConnection.js in the app
import ApiConnection from 'hiep294-apiconnection'
const todoAPIConnection = ApiConnection({
url: '/api/todos',
actions: ['index', 'create', 'update', 'delete']
})
export default todoAPIConnectionAbove file will exports to an object todoAPIConnection may include the following format in overview:
{
index: () => {}, /* if actions include 'index' */
create: () => {}, /* if actions include 'create' */
update: () => {}, /* if actions include 'update' */
delete: () => {}, /* if actions include 'delete' */
}In detail of todoAPIConnection
- Note:
handleSuccess,handleInvalid,handleFailedConnectionwhich are below are callbacks which are defined by own developer while developing front-end service, and not be defined by this module.
1. todoAPIConnection.index = (handleSuccess, handleFailedConnection) => {/ content code defined in 'hiep294-apiconnection' module /}
Next common process: handleSuccess(responseItems)
- when this method is called, if success, it will run
handleSuccess(responseTodos), withresponseTodosarray is filtered from API response. The client side can use them to print out in the screen
2. todoAPIConnection.create: (todoItem, handleSuccess, handleInvalid, handleFailedConnection) => {/ content code defined in 'hiep294-apiconnection' module /},
Input: todoItem is passed from client side
Next common processes: handleSuccess(responseItem) or handleInvalid(responseErrors)
- if creating
todoItemsuccessfully, it will run the methodhandleSuccess(responseItem), withresponseItemis filtered from API response, so the developer can use it to add in client. - if creating
todoItemun-successfully and because of invalid input, it will run the methodhandleInvalid(responseErrors), withresponseErrorsarray is filter from API response
3. todoAPIConnection.update = (todoItem, handleSuccess, handleInvalid, handleFailedConnection) => {/ content code defined in 'hiep294-apiconnection' module /},
Input: todoItem is passed from client side, and should include key _id
=> Next common processes: handleSuccess() or handleInvalid(responseErrors)
- if updating
todoItemsuccessfully, it will run the methodhandleSuccess(). - if updating
todoItemun-successfully and because of invalid input, it will run the moethodhandleInvalid(responseErrors), withresponseErrorsarray is filter from API response
4. todoAPIConnection.delete = (_id, handleSuccess, handleInvalid, handleFailedConnection) => {/ content code defined in 'hiep294-apiconnection' module /}
Input: _id of item in need of deleting
Next common processes: handleSuccess() or handleInvalid(responseErrors)
Change log
- 1.0.2: more info about example