Last active
February 27, 2018 07:38
-
-
Save Y2017/5a24655198eec495347f624a10d9f989 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Obvious API - REDUX | |
// https://hackernoon.com/o-api-an-alternative-to-rest-apis-e9a2ed53b93c | |
const ACTIONS = { | |
USERS: { | |
CART: { | |
ADD: 'ADD_PRODUCT_TO_CART', | |
}, | |
SIGN_IN: 'SIGN_IN', | |
SIGN_OUT: 'SIGN_OUT', | |
}, | |
PRODUCTS: { | |
GET_PRODUCT: 'GET_PRODUCT', | |
GET_PRODUCTS: 'GET_PRODUCTS', | |
ADD_PRODUCT_TO_CART: 'ADD_PRODUCT_TO_CART', | |
}, | |
}; | |
const handlers = { | |
[ACTIONS.PRODUCTS.ADD_PRODUCT_TO_CART]: require('./handlers/addProductToCart.js'), | |
[ACTIONS.PRODUCTS.GET_PRODUCT]: require('./handlers/getProduct.js'), | |
[ACTIONS.PRODUCTS.GET_PRODUCTS]: require('./handlers/getProducts.js'), | |
[ACTIONS.USERS.SIGN_IN]: require('./handlers/signIn.js'), | |
[ACTIONS.USERS.SIGN_OUT]: require('./handlers/signOut.js'), | |
}; | |
app.post('/api', (req, res) => { | |
const handler = handlers[req.body.action]; | |
if (handler) { | |
handler(req, res); | |
} else { | |
console.error(`${req.body.action} doesn't have a handler`); | |
res.sendStatus(500); // or whatever you want to do | |
} | |
}); | |
function addProductToCart(data) { | |
sendToServer('addProductToCart', data); | |
// also update the UI and maybe client-side store | |
} | |
function sendToServer(action, data) { | |
return fetch('/api', { | |
method: 'POST', | |
headers: { 'content-type': 'application/json' }, | |
body: JSON.stringify({ action, data }) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment