sg-node-api
Advanced tools
Comparing version 1.1.22 to 1.1.23
@@ -10,3 +10,8 @@ const errors = [ | ||
// Goal model | ||
{ code: 1103, message: 'Exception caught in model Goal::findByUser()' } | ||
{ code: 1102, message: 'Exception caught in model Goal::findById()' }, | ||
{ code: 1103, message: 'Exception caught in model Goal::findByUser()' }, | ||
// Contract model | ||
{ code: 1202, message: 'Exception caught in model Contract::findById()' }, | ||
{ code: 1203, message: 'Exception caught in model Contract::findByUser()' } | ||
] | ||
@@ -13,0 +18,0 @@ |
module.exports = { | ||
user: require('./models/User'), | ||
usergroup: require('./models/UserGroup'), | ||
goal: require('./models/Goal'), | ||
contract: require('./models/Contract'), | ||
commit: require('./models/Commit'), | ||
partner: require('./models/Partner'), | ||
link: require('./models/Link'), | ||
req: require('./utils/req') | ||
}; |
@@ -79,3 +79,3 @@ "use strict"; | ||
}).then( response => { | ||
let commits = response.map((commit) => (new Commit()).set(commit)) | ||
let commits = response.map( commit => (new Commit()).set(commit)) | ||
commits = self.sortItems(commits, 'createdAt', 'desc') | ||
@@ -102,3 +102,3 @@ return self.formatFields(commits) | ||
}).then( response => { | ||
let commits = response.map((commit) => (new Commit()).set(commit)) | ||
let commits = response.map( commit => (new Commit()).set(commit)) | ||
commits = self.sortItems(commits, 'createdAt', 'desc') | ||
@@ -121,3 +121,3 @@ return self.formatFields(commits) | ||
self.formatFields = (commits) => { | ||
return (commits || []).map((commit) => { | ||
return (commits || []).map( commit => { | ||
commit.set({ | ||
@@ -147,6 +147,3 @@ createdAt_human: moment(commit.get('createdAt')).fromNow(), // format('DD.MM.YYYY HH:mm'), | ||
*/ | ||
self.save2 = async(ctx) => { | ||
// Определяем данные для вставки или апдейта | ||
self.set({owner: { id: ctx.session.user.get('id')}}) | ||
self._save = self.save ; self.save = async(ctx) => { | ||
// Фиксируем текущую дату срабатывания в контракте и вычисляем следующую дату по контракту, сэйвим в контракт | ||
@@ -156,27 +153,15 @@ // const contract = self.get('contract') | ||
const data = self.plain() | ||
data.contract = { id: data.contract.id } | ||
if (self.get('id') !== null && typeof self.get('id') !== 'undefined') { | ||
// Если был определен айдишник - это апдейт, используем метод PUT | ||
await req.make(ctx, self.get('apiPath') + '/' + self.get('id'), Object.assign({}, data, { | ||
method: 'PUT', | ||
})).then( response => { | ||
self.set(response) | ||
}).catch( reason => { | ||
console.error(reason) | ||
return false | ||
}) | ||
} else { | ||
// Если не был определен айдишник - это вставка, используем метод POST | ||
await req.make(ctx, self.get('apiPath'), Object.assign({}, data, { | ||
method: 'POST', | ||
})).then( response => { | ||
self.set(response) | ||
}).catch( reason => { | ||
console.error(reason) | ||
return false | ||
}) | ||
} | ||
// Сохраняем в переменную текущее поле контракта | ||
const contractObject = self.get('contract') | ||
// Переопределяем поле контракта, чтобы была json-структура с полем id, а не объект модели Contract | ||
self.set({ contract: self.plain().contract }) | ||
// Вызываем дефолтный save()-метод, ничего не знающий о внутренних под-структурах | ||
await self._save(ctx) | ||
// И возвращаем на место контракт как объект | ||
self.set({ contract: contractObject }) | ||
return self | ||
@@ -183,0 +168,0 @@ } |
@@ -62,3 +62,5 @@ "use strict"; | ||
/** | ||
* TODO Понять нужен ли в модели этот метод или нужно оставить только в бэкендовой модели | ||
* Проверяет валидность введенной строки занятости: | ||
* | ||
* XXm|h every (day|mon|tue|...|week|month|XX,XX) | ||
@@ -95,2 +97,3 @@ * Примеры: | ||
/** | ||
* TODO Понять нужен ли в модели этот метод или нужно оставить только в бэкендовой модели | ||
* Парсит исходный формат занятости и возвращает форматированный для хранения в БД | ||
@@ -165,37 +168,31 @@ * | ||
* @param user_id - ID указанного пользователя | ||
* @returns {Promise.<TResult|null>} | ||
* @returns {Promise.<*>} | ||
*/ | ||
self.findByUser = async (ctx, user_id) => { | ||
const ret = await req.make(ctx, '/users/' + (user_id || ctx.session.user.get('id')) + '/contracts', { | ||
method: 'GET' | ||
}).then( response => { | ||
return response.map((contract) => { | ||
let c = (new Contract()).set(contract) | ||
let progress = 0 | ||
if (c.get('deadlineAt')) { | ||
progress = moment().startOf('day').diff(c.get('createdAt')) / moment(c.get('deadlineAt')).startOf('day').diff(c.get('createdAt')) * 100 | ||
c.set({ | ||
deadlineAt_human: moment(c.get('deadlineAt')), | ||
percent_completed: progress | ||
}) | ||
if (progress > 100) { | ||
c.set({overdue_days: moment().startOf('day').from(c.get('deadlineAt'), true)}) | ||
} | ||
} | ||
c.set({ | ||
state: c.get('completed') === true | ||
? 'Completed' | ||
: (c.get('archived') === true | ||
? 'Archived' | ||
: (progress === 100 ? 'Done' : (progress < 100 ? 'Active' : 'Overdue')) | ||
) | ||
}) | ||
return c | ||
const apiPath = self.get('apiPath') | ||
let result = { success: false } | ||
if (!apiPath || apiPath === '') { | ||
result.error = errors.getByCode(1001) // Wrong or undefined apiPath | ||
} else { | ||
user_id = (user_id && user_id.id) || user_id || ctx.session.user.get('id') | ||
await req.make(ctx, '/users/' + user_id + '/contracts', { | ||
method: 'GET' | ||
}).then( async response => { | ||
result.success = true | ||
result.items = response.items | ||
return true | ||
}).catch( reason => { | ||
result.error = Object.assign( | ||
{ object: reason }, | ||
errors.getByCode(1203) // Exception caught in model Goal::findByUser() | ||
) | ||
console.error(result.error.message) | ||
console.log(result.error.object) | ||
return false | ||
}) | ||
}).catch( reason => { | ||
console.error(reason) | ||
return false | ||
}) | ||
return ret || null | ||
} | ||
return result | ||
} | ||
@@ -202,0 +199,0 @@ |
@@ -5,3 +5,2 @@ "use strict"; | ||
const req = require('../utils/req') | ||
const moment = require('moment') | ||
const User = require('./User') | ||
@@ -43,51 +42,2 @@ const Contract = require('./Contract') | ||
/** | ||
* Возвращает массив всех целей выбранного или текущего пользователя | ||
* | ||
* @param ctx - Контекст приложения | ||
* @param user_id - Идентификатор пользователя | ||
* @returns {Promise.<*>} | ||
*/ | ||
self.findByUser = async (ctx, user_id) => { | ||
const apiPath = self.get('apiPath') | ||
let result = { success: false } | ||
if (!apiPath || apiPath === '') { | ||
result.error = errors.getByCode(1001) // Wrong or undefined apiPath | ||
} else { | ||
user_id = (user_id && user_id.id) || user_id || ctx.session.user.get('id') | ||
await req.make(ctx, '/users/' + user_id + '/goals', { | ||
method: 'GET' | ||
}).then( async response => { | ||
let goal | ||
result.success = true | ||
result.items = [] | ||
for (let i = 0; i < response.length; i++) { | ||
goal = (new Goal()).set(response[i]) | ||
let contract = await (new Contract()).findByGoalAndOwner(ctx, goal.get('id'), user_id) | ||
goal.set({ | ||
createdAt_human: moment(goal.get('createdAt')), | ||
updatedAt_human: moment(goal.get('updatedAt')), | ||
deadlineAt_human: goal.get('deadlineAt') ? moment(goal.get('deadlineAt')) : null, | ||
contract: contract.get() | ||
}) | ||
result.items.push(goal) | ||
} | ||
return true | ||
}).catch( reason => { | ||
result.error = Object.assign( | ||
{ object: reason }, | ||
errors.getByCode(1103) // Exception caught in model Goal::findByUser() | ||
) | ||
console.error(result.error.message) | ||
console.log(result.error.object) | ||
return false | ||
}) | ||
} | ||
return result | ||
} | ||
/** | ||
* Возвращает объект цели по ее идентификатору / пользователю и коду | ||
@@ -126,49 +76,63 @@ * | ||
* @param id - Идентификатор цели | ||
* @param user - Объект пользователя для определения поля текущего или указанного пользователя | ||
* @param opts - Другие опции | ||
* @returns {Promise.<*>} | ||
*/ | ||
self.findById = async (ctx, id, user, opts) => { | ||
opts = opts || {} | ||
const ret = await req.make(ctx, self.get('apiPath') + '/' + id, { | ||
self.findById = async (ctx, id) => { | ||
let result = { success: false } | ||
const response = await req.make(ctx, self.get('apiPath') + '/' + id, { | ||
method: 'GET' | ||
}).then( response => { | ||
self.set(response) | ||
result.success = true | ||
return true | ||
}).catch( reason => { | ||
console.error(reason) | ||
result.error = Object.assign( | ||
{ object: reason }, | ||
errors.getByCode(1102) // Exception caught in model Goal::findById() | ||
) | ||
console.error(result.error.message) | ||
console.log(result.error.object) | ||
return false | ||
}) | ||
if (ret !== false) { | ||
if (opts.simple !== true) { | ||
self.set({ | ||
createdAt_human: moment(self.get('createdAt')), | ||
updatedAt_human: moment(self.get('updatedAt')), | ||
contract: await (new Contract()).findByGoalAndOwner(ctx, self.get('id'), (user || ctx.session.user).get('id')), | ||
contracts: await (new Contract()).findByGoal(ctx, self.get('id')) | ||
}) | ||
let progress = 0 | ||
if (self.get('deadlineAt')) { | ||
progress = moment().startOf('day').diff(self.get('createdAt')) / moment(self.get('deadlineAt')).startOf('day').diff(self.get('createdAt')) * 100 | ||
self.set({ | ||
deadlineAt_human: moment(self.get('deadlineAt')), | ||
percent_completed: progress | ||
}) | ||
if (progress > 100) { | ||
self.set({overdue_days: moment().startOf('day').from(self.get('deadlineAt'), true)}) | ||
} | ||
} | ||
self.set({ | ||
state: self.get('completed') === true | ||
? 'Completed' | ||
: (self.get('archived') === true | ||
? 'Archived' | ||
: (progress === 100 ? 'Done' : (progress < 100 ? 'Active' : 'Overdue')) | ||
) | ||
}) | ||
} | ||
return self | ||
if (response === true) { | ||
result = self | ||
} | ||
return result | ||
} | ||
/** | ||
* Возвращает массив всех целей выбранного или текущего пользователя | ||
* | ||
* @param ctx - Контекст приложения | ||
* @param user_id - Идентификатор пользователя | ||
* @returns {Promise.<*>} | ||
*/ | ||
self.findByUser = async (ctx, user_id) => { | ||
const apiPath = self.get('apiPath') | ||
let result = { success: false } | ||
if (!apiPath || apiPath === '') { | ||
result.error = errors.getByCode(1001) // Wrong or undefined apiPath | ||
} else { | ||
return null | ||
user_id = (user_id && user_id.id) || user_id || ctx.session.user.get('id') | ||
await req.make(ctx, '/users/' + user_id + '/goals', { | ||
method: 'GET' | ||
}).then( async response => { | ||
result.success = true | ||
result.items = response.items | ||
return true | ||
}).catch( reason => { | ||
result.error = Object.assign( | ||
{ object: reason }, | ||
errors.getByCode(1103) // Exception caught in model Goal::findByUser() | ||
) | ||
console.error(result.error.message) | ||
console.log(result.error.object) | ||
return false | ||
}) | ||
} | ||
return result | ||
} | ||
@@ -175,0 +139,0 @@ |
@@ -32,3 +32,5 @@ "use strict"; | ||
method: 'POST' | ||
}).then(response => response) | ||
}).then(response => { | ||
return response | ||
}) | ||
.catch(reason => { | ||
@@ -148,4 +150,4 @@ console.error(reason) | ||
if (auth.token) { | ||
console.log('Сессия обновлена, инфо:') | ||
console.log(ctx.session.passport.user) | ||
console.log('Сессия обновлена') | ||
// console.log('Инфо: ', ctx.session.passport.user) | ||
ctx.session.passport.user = ctx.session.user.set({token: auth.token}).get() | ||
@@ -152,0 +154,0 @@ return { success: true } |
{ | ||
"name": "sg-node-api", | ||
"version": "1.1.22", | ||
"version": "1.1.23", | ||
"description": "Shared Goals API implemented as Node.JS library. API for telegram bot, www-clients and other usages", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -101,7 +101,14 @@ "use strict"; | ||
let responseJSON = null | ||
try { | ||
responseJSON = JSON.parse(body) | ||
} catch (err) { | ||
console.error('body: ', body) | ||
console.error(ctx, err) | ||
if (body.match(/Authentication Error/)) { | ||
reject({success: false, error: {message: body}}) | ||
} else if (body.match(/Internal Server Error/)) { | ||
reject({success: false, error: {message: body}}) | ||
} else { | ||
try { | ||
responseJSON = JSON.parse(body) | ||
} catch (err) { | ||
console.log('body: ', body) | ||
// console.error('context:', ctx) | ||
console.error('error:', err) | ||
} | ||
} | ||
@@ -114,2 +121,4 @@ if (responseJSON !== null) { | ||
} | ||
} else { | ||
reject({success: false, error: {message: body}}) | ||
} | ||
@@ -116,0 +125,0 @@ } else { |
Sorry, the diff of this file is not supported yet
111851
22
1379