import * as Joi from 'joi' import { OystAPIS, logs, makeError, replies } from '@oyst/utils' import { isEmpty, merge, pick } from 'ramda' import PaymentApi from '../../../apis/payment' import UserApi from '../../../apis/user' import authorizeHandler from '../../../handlers/authorize' import { authorize as headers } from '../../../validators/headers' import log from '../../../lib/log' import { card as payload } from '../../../validators/users' import sessionHandler from '../../../handlers/session' import { toSnake } from 'convert-keys' const { error, success } = replies export default { config: { pre: [sessionHandler, authorizeHandler], validate: { headers, payload } }, handler: async (req, reply) => { const userId = req.pre.session.user_id as string const encryptedCard = req.payload.encrypted_card try { console.log('calling checkBinCard', { encryptedCard }) const card = await PaymentApi.checkBinCard(toSnake({ encryptedCard })) console.log('calling canUse', { cardId: card.id, userId }) const { can_link, reason } = await UserApi.canLinkCard(toSnake({ cardId: card.id, userId })) if (!can_link) { return error(makeError('CLICK-409', `cannot-link-card:${reason}`)) } console.log('calling PaymentApi.addCard', { encryptedCard }) await PaymentApi.addCard(toSnake({ encryptedCard })) console.log('calling UserApi.addCard', { userId, card }) await UserApi.addCard(toSnake({ userId, card })) console.log('calling setPrimaryCard', { cardId: card.id, userId }) await UserApi.setPrimaryCard(toSnake({ cardId: card.id, userId })) console.log('calling findById', { userId }) const user = await UserApi.findById(userId) success({ user }, reply) } catch (err) { logs.error(err) error(makeError(err), reply) } }, method: 'POST', path: '/v1/users/cards' }