Last active
March 24, 2017 15:13
-
-
Save TheSirop/2f9d664c1d73be564d8724adb838cecb to your computer and use it in GitHub Desktop.
Сохранение заказа и отправка данных в 1С через API
This file contains hidden or 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
| import config from 'config'; | |
| import Order from '../models/order'; | |
| import Cart from '../models/cart'; | |
| const axios = require('axios'); | |
| export async function postCheckout(req, res, next) { | |
| if (!req.session.cart) { | |
| return res.redirect('/cart'); | |
| } | |
| let cart; | |
| let order; | |
| let post; | |
| const apiConfig = { | |
| timeout: 1000, | |
| headers: { 'Content-Type': 'application/json' }, | |
| auth: { | |
| username: config.remoteApiLogin, | |
| password: config.remoteApiPassword, | |
| }, | |
| }; | |
| try { | |
| cart = await new Cart(req.session.cart); | |
| } catch ({ message }) { | |
| return next({ | |
| status: 500, | |
| message, | |
| }); | |
| } | |
| try { | |
| order = await new Order({ | |
| user: req.user, | |
| cart, | |
| }); | |
| } catch ({ message }) { | |
| return next({ | |
| status: 500, | |
| message, | |
| }); | |
| } | |
| // Сохраняем заказ в БД | |
| try { | |
| await order.save(); | |
| } catch ({ message }) { | |
| return next({ | |
| status: 500, | |
| message, | |
| }); | |
| } | |
| /* Забираем последний заказ из БД | |
| * Почему забираем заказ из БД, а не сразу массив order постим в 1С? | |
| * Дело в том, что нам важен ID который присвоится заказу при сохранении в базу. | |
| * Забрав данные о последнем заказе, мы получим и нужный нам ID-заказа (_id) | |
| */ | |
| try { | |
| post = await Order.findOne({}, {}, { sort: { createdAt: -1 } }); | |
| global.console.log(post); | |
| } catch ({ message }) { | |
| return next({ | |
| status: 500, | |
| message, | |
| }); | |
| } | |
| // Отправляем данные в 1С | |
| try { | |
| await axios.post(config.postOrder, post, apiConfig); | |
| } catch ({ message }) { | |
| return next({ | |
| status: 500, | |
| message, | |
| }); | |
| } | |
| req.session.cart = null; | |
| return res.redirect('/user/profile'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment