Skip to content

Commit

Permalink
orders & question services: stop using static service methods, use st…
Browse files Browse the repository at this point in the history
…ateless instance model instead.
  • Loading branch information
tmilar committed Jul 18, 2019
1 parent 46e4db6 commit e889529
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 51 deletions.
2 changes: 1 addition & 1 deletion lib/sheets-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ class SheetsHelper {
await this.googleSpreadsheet.useServiceAccountAuthAsync(credentials)

const info = await this.getInfoAboutSpreadsheet()
console.log(`\u001B[34mLoaded document: \u001B[35m${info.title} - \u001B[34mSheet name: \u001B[35m${sheetName}`)

this.sheet = this.googleSpreadsheet.worksheets.find(sheet => sheet.title === sheetName)

if (!this.sheet) {
throw new Error(`Sheet ${sheetName} not found for sheet key ${spreadsheetsKey}.`)
}
console.log(`\u001B[34mConnected to document: \u001B[35m${info.title} - \u001B[34mSheet name: \u001B[35m${sheetName}`)
}

async getInfoAboutSpreadsheet() {
Expand Down
2 changes: 1 addition & 1 deletion model/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ accountSchema.statics.findAllByCurrentClientId = function () {
let allAccounts = null

accountSchema.statics.findAllCached = async function () {
if (allAccounts) {
if (allAccounts && allAccounts.length > 0) {
return allAccounts
}

Expand Down
70 changes: 39 additions & 31 deletions service/orders.service.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,65 @@
const SheetsHelper = require('../lib/sheets-helper')
const Order = require('../model/order.js')
const Account = require('../model/account')
const Order = require('../model/order')
const config = require('../config')
const MeliClient = require('../lib/meli-client.js')
const MeliClient = require('../lib/meli-client')

class OrdersService {
/**
* Setup Order service spreadsheet reference.
*
* Setup & Create a new OrderService instance.
* @return {OrdersService} ordersService new instance
*/
static async setup() {
this.setupMeliClient()
await this.setupOrdersSheet()

console.log('[OrdersService] setup ready')
}

static setupMeliClient() {
if (this.meliClient) {
return
}

this.meliClient = new MeliClient()
static async build() {
const [ordersSheet, meliClient] = await Promise.all([
this.setupOrdersSheet(),
this.setupMeliClient()
])
return new OrdersService(ordersSheet, meliClient)
}

static async setupOrdersSheet() {
if (this.ordersSheet) {
return
}

const ordersSpreadsheet = config.spreadsheet.orders

this.ordersSheet = new SheetsHelper()
this.headerRowHeight = 1
this.headerRowWidth = Order.getColumns().keys().length
const ordersSheet = new SheetsHelper()
const headerRowHeight = 1
const headerRowWidth = Order.getColumns().keys().length

await this.ordersSheet.setupSheet({
await ordersSheet.setupSheet({
credentials: config.auth.spreadsheet,
spreadsheetsKey: ordersSpreadsheet.id,
sheetName: ordersSpreadsheet.sheet,
headerRowHeight: this.headerRowHeight,
headerRowWidth: this.headerRowWidth
headerRowHeight,
headerRowWidth
})
return ordersSheet
}

static async saveOrUpdateOrder(orderJson) {
static async setupMeliClient() {
const accounts = await Account.findAllCached()
const meliClient = new MeliClient()
accounts.forEach(account => meliClient.addAccount(account))
console.log(`[OrdersService] Using accounts: '${meliClient.accounts.map(({nickname}) => nickname).join('\', \'')}'`)
return meliClient
}

/**
* @private constructor, use build() method to create a new instance instead.
* @param {*} ordersSheet - the orders sheet reference
* @param {*} meliClient - meli client reference
*/
constructor(ordersSheet, meliClient) {
this.ordersSheet = ordersSheet
this.meliClient = meliClient
}

async saveOrUpdateOrder(orderJson) {
const order = Order.buildFromMeliOrder(orderJson)
const orderRow = order.toRowArray()
const {colPos: orderIdColumn} = Order.getIdColumn()
console.log('Saving order row...')
await this.ordersSheet.updateOrAppendRow(orderRow, orderIdColumn)
}


/**
* For all accounts, fetch all Meli orders between desired dates.
*
Expand All @@ -62,7 +70,7 @@ class OrdersService {
*
* @returns {[*]} all the meli orders for the selected accounts, ordered by date_closed.
*/
static async fetchMeliOrders({startDate, endDate, accounts, id}) {
async fetchMeliOrders({startDate, endDate, accounts, id}) {
const ordersResponses = await this.meliClient.getOrders({startDate, endDate, accounts, id})

// Flatten responses to one array
Expand All @@ -89,7 +97,7 @@ class OrdersService {
*
* @returns {Promise.<{}|null>} - resolves order object, or null if not found
*/
static async fetchOneMeliOrder(account, id) {
async fetchOneMeliOrder(account, id) {
const orders = await this.fetchMeliOrders({accounts: [account], id})
return (orders && orders.length > 0) ? orders[0] : null
}
Expand Down
54 changes: 36 additions & 18 deletions service/questions.service.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,55 @@
const config = require('../config')
const MeliClient = require('../lib/meli-client.js')
const MeliClient = require('../lib/meli-client')
const SheetsHelper = require('../lib/sheets-helper')
const Account = require('../model/account')
const QuestionMapper = require('../model/question-mapper')

class QuestionsService {
static async setup() {
this.setupMeliClient()
await this.setupQuestionsSheet()
/**
* Setup & Create a new QuestionsService instance.
* @return {QuestionsService} questionService new instance
*/
static async build() {
const [questionsSheet, meliClient] = await Promise.all([
this.setupQuestionsSheet(),
this.setupMeliClient()
])

console.log('[QuestionsService] setup ready')
}

static setupMeliClient() {
this.meliClient = new MeliClient()
return new QuestionsService(questionsSheet, meliClient)
}

static async setupQuestionsSheet() {
const questionsSpreadsheet = config.spreadsheet.questions

this.questionsSheet = new SheetsHelper()
this.headerRowHeight = 1
this.headerRowWidth = QuestionMapper.getColumns().keys().length
const questionsSheet = new SheetsHelper()
const headerRowHeight = 1
const headerRowWidth = QuestionMapper.getColumns().keys().length

await this.questionsSheet.setupSheet({
await questionsSheet.setupSheet({
credentials: config.auth.spreadsheet,
spreadsheetsKey: questionsSpreadsheet.id,
sheetName: questionsSpreadsheet.sheet,
headerRowHeight: this.headerRowHeight,
headerRowWidth: this.headerRowWidth
headerRowHeight,
headerRowWidth
})

return questionsSheet
}

static async setupMeliClient() {
const accounts = await Account.findAllCached()
const meliClient = new MeliClient()
accounts.forEach(account => meliClient.addAccount(account))
console.log(`[QuestionsService] Using accounts: '${meliClient.accounts.map(({nickname}) => nickname).join('\', \'')}'`)
return meliClient
}

constructor(questionsSheet, meliClient) {
this.questionsSheet = questionsSheet
this.meliClient = meliClient
}

static async saveOrUpdateQuestion(sellerAccount, question) {
async saveOrUpdateQuestion(sellerAccount, question) {
if (typeof question === 'number' || typeof question === 'string') {
// 'question' is id - retrieve remaining question data
const questionId = question
Expand All @@ -48,12 +66,12 @@ class QuestionsService {
await this.questionsSheet.updateOrAppendRow(questionRow, idColumn)
}

static async answerQuestion(sellerId, questionId, answerText) {
async answerQuestion(sellerId, questionId, answerText) {
const answeringAccount = await this.meliClient.getUser(sellerId)
return this.meliClient.postQuestionAnswer(answeringAccount, questionId, answerText)
}

static async getQuestions({accounts, status, startDate, endDate}) {
getQuestions({accounts, status, startDate, endDate}) {
return this.meliClient.getQuestions({accounts, status, startDate, endDate})
}
}
Expand Down

0 comments on commit e889529

Please sign in to comment.