pagaris
Version:
Pagaris API client for Node
89 lines (74 loc) • 2.49 kB
JavaScript
const Client = require('./client')
const CANNOT_CREATE_MESSAGE = 'Cannot call `Order.prototype.create()` on an '+
'`Order` which already has an `id`'
const CANNOT_CONFIRM_MESSAGE = 'Cannot call `Order.prototype.confirm()` on an '+
'non-persisted `Order`. Maybe you have not called '+
'`Order.prototype.create()` yet?'
const CANNOT_CANCEL_MESSAGE = 'Cannot call `Order.prototype.cancel()` on an '+
'non-persisted `Order`. Maybe you have not called '+
'`Order.prototype.create()` yet?'
class Order {
constructor(options) {
if (options) {
this.amount = options.amount
this.metadata = options.metadata
this.products = options.products
this.redirectUrl = options.redirectUrl
}
}
create() {
if (this.id) throw CANNOT_CREATE_MESSAGE
return Client.post('orders', {
amount: this.amount,
metadata: this.metadata,
products: this.products,
redirect_url: this.redirectUrl
}).then(res => this.updateFromResponse(res.order))
}
confirm() {
if (!this.id) throw CANNOT_CONFIRM_MESSAGE
return Client.put(`orders/${this.id}/confirm`)
.then(res => this.updateFromResponse(res.order))
}
cancel() {
if (!this.id) throw CANNOT_CANCEL_MESSAGE
return Client.put(`orders/${this.id}/cancel`)
.then(res => this.updateFromResponse(res.order))
}
static all() {
return Client.get('orders')
.then(res => {
return res.orders.map(responseOrder => {
let order = new Order()
return order.updateFromResponse(responseOrder)
})
})
}
static get(id) {
return Client.get(`orders/${id}`).then(res => {
return (new Order()).updateFromResponse(res.order)
})
}
static create(options) {
let order = new Order(options)
return order.create()
}
/**
* Transforms a response Order values and sets them.
*/
updateFromResponse(order) {
this.id = order.id
this.amount = order.amount && parseFloat(order.amount)
this.fee = order.fee && parseFloat(order.fee)
this.payoutAmount = order.payout_amount && parseFloat(order.payout_amount)
this.status = order.status
this.metadata = order.metadata
this.products = order.products
this.redirectUrl = order.redirect_url
this.createdAt = order.created_at && new Date(order.created_at)
this.updatedAt = order.updated_at && new Date(order.updated_at)
this.url = order.url
return this
}
}
module.exports = Order;