From b9822912e9025e3ef6417a3a9ca1a9a9ccec13d7 Mon Sep 17 00:00:00 2001 From: Lucas Rocha Date: Tue, 4 Feb 2020 19:03:55 -0300 Subject: [PATCH] [Bugfix] Bug fixes Removing the subscribe feature from application. --- .env.example | 10 - .../handler/user.delete.event.handler.ts | 18 -- .../fitbit.auth.data.repository.interface.ts | 6 - .../fitbit.client.repository.interface.ts | 6 - .../port/user.auth.data.service.interface.ts | 2 - .../service/user.auth.data.service.ts | 113 +---------- src/di/di.ts | 3 - src/di/identifiers.ts | 1 - .../repository/fitbit.client.repository.ts | 37 ---- .../repository/fitbit.data.repository.ts | 182 +----------------- .../fitbit.subscriber.controller.ts | 29 --- .../fitbit.subscriber.controller.spec.ts | 52 ----- .../fitbit.data.repository.spec.ts | 38 ---- .../services/user.auth.data.service.spec.ts | 12 -- 14 files changed, 5 insertions(+), 504 deletions(-) delete mode 100644 src/ui/controllers/fitbit.subscriber.controller.ts delete mode 100644 test/integration/routes/fitbit.subscriber.controller.spec.ts diff --git a/.env.example b/.env.example index ef6afc6..7081eb1 100644 --- a/.env.example +++ b/.env.example @@ -86,16 +86,6 @@ FITBIT_CLIENT_ID=CIENT_ID_HERE # default value: CIENT_SECRET_HERE FITBIT_CLIENT_SECRET=CIENT_SECRET_HERE -# FITBIT_CLIENT_SUBSCRIBER: Client Subscriber code for automatically get notification from new -# sync data. -# default value: CLIENT_SUBSCRIBER_HERE -FITBIT_CLIENT_SUBSCRIBER=CLIENT_SUBSCRIBER_HERE - -# FITBIT_SUBSCRIBER_ID: Customer Subscriber ID, used to manage the subscriber who will -# receive notification of a user resource. -# default value: SUBSCRIBER_ID_HERE -FITBIT_SUBSCRIBER_ID=SUBSCRIBER_ID_HERE - ################################################################################################# ################################# DATA SYNC ENVIRONMENT SETUP ################################### ################################################################################################# diff --git a/src/application/integration-event/handler/user.delete.event.handler.ts b/src/application/integration-event/handler/user.delete.event.handler.ts index d6cf818..10b9276 100644 --- a/src/application/integration-event/handler/user.delete.event.handler.ts +++ b/src/application/integration-event/handler/user.delete.event.handler.ts @@ -5,7 +5,6 @@ import { DIContainer } from '../../../di/di' import { ValidationException } from '../../domain/exception/validation.exception' import { IUserAuthDataRepository } from '../../port/user.auth.data.repository.interface' import { Query } from '../../../infrastructure/repository/query/query' -import { IFitbitDataRepository } from '../../port/fitbit.auth.data.repository.interface' import { UserAuthData } from '../../domain/model/user.auth.data' import { IResourceRepository } from '../../port/resource.repository.interface' @@ -19,8 +18,6 @@ export const userDeleteEventHandler = async (event: any) => { const logger: ILogger = DIContainer.get(Identifier.LOGGER) const userAuthDataRepo: IUserAuthDataRepository = DIContainer.get(Identifier.USER_AUTH_DATA_REPOSITORY) - const fitbitAuthDataRepo: IFitbitDataRepository = - DIContainer.get(Identifier.FITBIT_DATA_REPOSITORY) const resourceRepo: IResourceRepository = DIContainer.get(Identifier.RESOURCE_REPOSITORY) try { @@ -37,21 +34,6 @@ export const userDeleteEventHandler = async (event: any) => { const query: Query = new Query().fromJSON({ filters: { user_id: childId } }) const userAuthData: UserAuthData = await userAuthDataRepo.findOne(query) if (userAuthData) { - if (userAuthData.fitbit!.scope!) { - const payload: any = await fitbitAuthDataRepo.getTokenPayload(userAuthData.fitbit!.access_token!) - if (payload || payload.scopes) { - const scopes: Array = payload.scopes.split(' ') - if (scopes.includes('rwei')) { // Scope reference from fitbit to weight data is rwei - await fitbitAuthDataRepo.unsubscribeUserEvent(userAuthData.fitbit!, 'body', 'BODY') - } - if (scopes.includes('ract')) { // Scope reference from fitbit to activity data is ract - await fitbitAuthDataRepo.unsubscribeUserEvent(userAuthData.fitbit!, 'activities', 'ACTIVITIES') - } - if (scopes.includes('rsle')) { // Scope reference from fitbit to sleep data is rsle - await fitbitAuthDataRepo.unsubscribeUserEvent(userAuthData.fitbit!, 'sleep', 'SLEEP') - } - } - } await userAuthDataRepo.deleteByQuery(query) await resourceRepo.deleteByQuery(query) // 3. If got here, it's because the action was successful. diff --git a/src/application/port/fitbit.auth.data.repository.interface.ts b/src/application/port/fitbit.auth.data.repository.interface.ts index b5cbe4b..935697a 100644 --- a/src/application/port/fitbit.auth.data.repository.interface.ts +++ b/src/application/port/fitbit.auth.data.repository.interface.ts @@ -16,11 +16,5 @@ export interface IFitbitDataRepository { syncFitbitData(data: FitbitAuthData, userId: string): Promise - syncLastFitbitData(data: FitbitAuthData, userId: string, type: string, date: string): Promise - - subscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise - - unsubscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise - getTokenPayload(token: string): Promise } diff --git a/src/application/port/fitbit.client.repository.interface.ts b/src/application/port/fitbit.client.repository.interface.ts index dd2d8f9..300127a 100644 --- a/src/application/port/fitbit.client.repository.interface.ts +++ b/src/application/port/fitbit.client.repository.interface.ts @@ -1,13 +1,7 @@ -import { FitbitAuthData } from '../domain/model/fitbit.auth.data' - export interface IFitbitClientRepository { revokeToken(accessToken: string): Promise refreshToken(accessToken: string, refreshToken: string, expiresIn?: number): Promise getDataFromPath(path: string, accessToken: string): Promise - - subscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise - - unsubscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise } diff --git a/src/application/port/user.auth.data.service.interface.ts b/src/application/port/user.auth.data.service.interface.ts index f506b9b..9c1abd0 100644 --- a/src/application/port/user.auth.data.service.interface.ts +++ b/src/application/port/user.auth.data.service.interface.ts @@ -8,6 +8,4 @@ export interface IUserAuthDataService extends IService { revokeFitbitAccessToken(userId: string): Promise syncFitbitDataFromUser(userId: string): Promise - - syncLastFitbitUserData(fitbitUserId: string, type: string, date: string): Promise } diff --git a/src/application/service/user.auth.data.service.ts b/src/application/service/user.auth.data.service.ts index 94056cb..9b96d05 100644 --- a/src/application/service/user.auth.data.service.ts +++ b/src/application/service/user.auth.data.service.ts @@ -30,10 +30,9 @@ export class UserAuthDataService implements IUserAuthDataService { try { const authData: UserAuthData = await this.manageFitbitAuthData(item) CreateUserAuthDataValidator.validate(item) - let result: UserAuthData = new UserAuthData() + let result: UserAuthData authData.fitbit!.status = 'valid_token' - await this.subscribeFitbitEvents(item) const alreadySaved: UserAuthData = await this._userAuthDataRepo .findOne(new Query().fromJSON({ filters: { user_id: authData.user_id! } })) @@ -94,16 +93,13 @@ export class UserAuthDataService implements IUserAuthDataService { return resolve() } - // 2. Unsubscribe from Fitbit events. - await this.unsubscribeFitbitEvents(authData) - - // 3. Revokes Fitbit access token. + // 2. Revokes Fitbit access token. const isRevoked: boolean = await this._fitbitAuthDataRepo.revokeToken(authData.fitbit.access_token) - // 4. Remove Fitbit authorization data from local database. + // 3. Remove Fitbit authorization data from local database. const isRemoved: boolean = await this._fitbitAuthDataRepo.removeFitbitAuthData(userId) - // 5. Publish the Fitbit revoke event on the bus. + // 4. Publish the Fitbit revoke event on the bus. if (isRevoked && isRemoved) { this._eventBus.bus .pubFitbitRevoke({ child_id: userId }) @@ -191,107 +187,6 @@ export class UserAuthDataService implements IUserAuthDataService { }) } - public async syncLastFitbitUserData(fitbitUserId: string, type: string, date: string): Promise { - try { - const authData: UserAuthData = - await this._userAuthDataRepo - .findOne(new Query().fromJSON({ filters: { 'fitbit.user_id': fitbitUserId } })) - if (!authData) return await Promise.resolve() - this.syncLastFitbitData(authData.fitbit!, authData.user_id!, type, date) - .then() - .catch(err => this._logger.error(`The resource ${type} from ${authData.user_id} could note be sync: ` + - err.message)) - return await Promise.resolve() - } catch (err) { - return await Promise.reject(err) - } - } - - private async syncLastFitbitData(data: FitbitAuthData, userId: string, type: string, date: string): Promise { - try { - VerifyFitbitAuthValidator.validate(data) - await this._fitbitAuthDataRepo.syncLastFitbitData(data, userId, type, date) - return Promise.resolve() - } catch (err) { - if (err.type) { - if (err.type === 'expired_token') { - try { - const newToken: FitbitAuthData = - await this._fitbitAuthDataRepo.refreshToken(userId, data.access_token!, data.refresh_token!) - this.syncLastFitbitData(newToken, userId, type, date) - .then() - .catch(err => { - this.updateTokenStatus(userId, err.type) - this.publishFitbitAuthError(err, userId) - return Promise.reject(err) - }) - } catch (err) { - if (err.type !== 'system') this.updateTokenStatus(userId, err.type) - this.publishFitbitAuthError(err, userId) - return Promise.reject(err) - } - } else if (err.type === 'client_error') { - try { - await this.syncFitbitData(data, userId) - } catch (err) { - return Promise.reject(err) - } - } else { - if (err.type !== 'system') this.updateTokenStatus(userId, err.type) - this.publishFitbitAuthError(err, userId) - return Promise.reject(err) - } - } else { - return await Promise.reject(err) - } - } - } - - private async subscribeFitbitEvents(data: UserAuthData): Promise { - return new Promise(async (resolve, reject) => { - try { - if (!data || !data.fitbit || !data.fitbit.scope) return - - const scopes: Array = data.fitbit.scope.split(' ') - - if (scopes.includes('rwei')) { // Scope reference from fitbit to weight data is rwei - await this._fitbitAuthDataRepo.subscribeUserEvent(data.fitbit!, 'body', 'BODY') - } - if (scopes.includes('ract')) { // Scope reference from fitbit to activity data is ract - await this._fitbitAuthDataRepo.subscribeUserEvent(data.fitbit!, 'activities', 'ACTIVITIES') - } - if (scopes.includes('rsle')) { // Scope reference from fitbit to sleep data is rsle - await this._fitbitAuthDataRepo.subscribeUserEvent(data.fitbit!, 'sleep', 'SLEEP') - } - return resolve() - } catch (err) { - return reject(err) - } - }) - } - - private async unsubscribeFitbitEvents(data: UserAuthData): Promise { - return new Promise(async (resolve, reject) => { - try { - if (!data || !data.fitbit || !data.fitbit.scope) return - - const scopes: Array = data.fitbit.scope.split(' ') - if (scopes.includes('rwei')) { // Scope reference from fitbit to weight data is rwei - await this._fitbitAuthDataRepo.unsubscribeUserEvent(data.fitbit!, 'body', 'BODY') - } - if (scopes.includes('ract')) { // Scope reference from fitbit to activity data is ract - await this._fitbitAuthDataRepo.unsubscribeUserEvent(data.fitbit!, 'activities', 'ACTIVITIES') - } - if (scopes.includes('rsle')) { // Scope reference from fitbit to sleep data is rsle - await this._fitbitAuthDataRepo.unsubscribeUserEvent(data.fitbit!, 'sleep', 'SLEEP') - } - return resolve() - } catch (err) { - return reject(err) - } - }) - } - private async manageFitbitAuthData(data: UserAuthData): Promise { return new Promise(async (resolve, reject) => { try { diff --git a/src/di/di.ts b/src/di/di.ts index eb152ef..b8732e3 100644 --- a/src/di/di.ts +++ b/src/di/di.ts @@ -17,7 +17,6 @@ import { IEntityMapper } from '../infrastructure/port/entity.mapper.interface' import { UserAuthDataService } from '../application/service/user.auth.data.service' import { IBackgroundTask } from '../application/port/background.task.interface' import { SyncFitbitDataTask } from '../background/task/sync.fitbit.data.task' -import { FitbitSubscriberController } from '../ui/controllers/fitbit.subscriber.controller' import { FitbitAuthDataEntityMapper } from '../infrastructure/entity/mapper/fitbit.auth.data.entity.mapper' import { UserAuthData } from '../application/domain/model/user.auth.data' import { UserAuthDataEntity } from '../infrastructure/entity/user.auth.data.entity' @@ -76,8 +75,6 @@ class IoC { // Controllers this._container.bind(Identifier.HOME_CONTROLLER).to(HomeController).inSingletonScope() this._container.bind(Identifier.FITBIT_CONTROLLER).to(FitbitController).inSingletonScope() - this._container.bind(Identifier.FITBIT_SUBSCRIBER_CONTROLLER) - .to(FitbitSubscriberController).inSingletonScope() this._container.bind(Identifier.USER_FITBIT_AUTH_CONTROLLER) .to(UserFitbitAuthController).inSingletonScope() this._container.bind(Identifier.USER_FITBIT_SYNC_CONTROLLER) diff --git a/src/di/identifiers.ts b/src/di/identifiers.ts index 450f509..af3bc41 100644 --- a/src/di/identifiers.ts +++ b/src/di/identifiers.ts @@ -8,7 +8,6 @@ export abstract class Identifier { // Controllers public static readonly HOME_CONTROLLER: any = Symbol.for('HomeController') - public static readonly FITBIT_SUBSCRIBER_CONTROLLER: any = Symbol.for('FitbitSubscriberController') public static readonly FITBIT_CONTROLLER: any = Symbol.for('FitbitController') public static readonly USER_FITBIT_AUTH_CONTROLLER: any = Symbol.for('UserFitbitAuthController') public static readonly USER_FITBIT_SYNC_CONTROLLER: any = Symbol.for('UserFitbitSyncController') diff --git a/src/infrastructure/repository/fitbit.client.repository.ts b/src/infrastructure/repository/fitbit.client.repository.ts index 4db902d..dd4704f 100644 --- a/src/infrastructure/repository/fitbit.client.repository.ts +++ b/src/infrastructure/repository/fitbit.client.repository.ts @@ -47,43 +47,6 @@ export class FitbitClientRepository implements IFitbitClientRepository { }) } - public async subscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise { - return new Promise((resolve, reject) => { - this.fitbit_client - .post( - `/${resource}/apiSubscriptions/${subscriptionId}-${data.user_id}.json`, // Path - data.access_token, // Access Token - null, // Form Data - null, // User Id - { 'X-Fitbit-Subscriber-Id': process.env.FITBIT_SUBSCRIBER_ID } // Extra Header - ) - .then(res => { - if (res[0].errors) { - return reject(this.fitbitClientErrorListener(res[0].errors[0])) - } - return resolve() - }).catch(err => reject(this.fitbitClientErrorListener(err))) - }) - } - - public async unsubscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise { - return new Promise((resolve, reject) => { - this.fitbit_client - .delete( - `/${resource}/apiSubscriptions/${subscriptionId}-${data.user_id}.json`, // Path - data.access_token, // Access Token - null, // User Id - { 'X-Fitbit-Subscriber-Id': process.env.FITBIT_SUBSCRIBER_ID } // Extra Header - ) - .then(res => { - if (res[0] && res[0].errors) { - return reject(this.fitbitClientErrorListener(res[0].errors[0])) - } - return resolve() - }).catch(err => reject(this.fitbitClientErrorListener(err))) - }) - } - private fitbitClientErrorListener(err: any): OAuthException | FitbitClientException | undefined { if (err.context) return new OAuthException(err.context.errors[0].errorType, err.context.errors[0].message) else if (err.code === 'EAI_AGAIN') return new FitbitClientException('client_error', err.message) diff --git a/src/infrastructure/repository/fitbit.data.repository.ts b/src/infrastructure/repository/fitbit.data.repository.ts index 4080fd0..465b95c 100644 --- a/src/infrastructure/repository/fitbit.data.repository.ts +++ b/src/infrastructure/repository/fitbit.data.repository.ts @@ -93,26 +93,6 @@ export class FitbitDataRepository implements IFitbitDataRepository { } } - public async subscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise { - try { - await this._fitbitClientRepo.subscribeUserEvent(data, resource, subscriptionId) - this._logger.info(`Successful subscribe on ${resource} resource from user ${data.user_id}.`) - return Promise.resolve() - } catch (err) { - return Promise.reject(this.fitbitClientErrorListener(err, data.access_token!, data.refresh_token!)) - } - } - - public async unsubscribeUserEvent(data: FitbitAuthData, resource: string, subscriptionId: string): Promise { - try { - await this._fitbitClientRepo.unsubscribeUserEvent(data, resource, subscriptionId) - this._logger.info(`Successful unsubscribe on ${resource} resource from user ${data.user_id}.`) - return Promise.resolve() - } catch (err) { - return Promise.reject(this.fitbitClientErrorListener(err, data.access_token!, data.refresh_token!)) - } - } - public async syncFitbitData(data: FitbitAuthData, userId: string): Promise { return new Promise(async (resolve, reject) => { try { @@ -254,24 +234,6 @@ export class FitbitDataRepository implements IFitbitDataRepository { }) } - public async syncLastFitbitData(data: FitbitAuthData, userId: string, type: string, date: string): Promise { - try { - if (type === ResourceDataType.BODY) await this.syncLastFitbitUserWeight(data, userId, date) - else if (type === ResourceDataType.ACTIVITIES) { - await this.syncLastFitbitUserActivity(data, userId, date) - await this.syncLastFitbitUserActivityLogs(data, userId, date) - } else if (type === ResourceDataType.SLEEP) await this.syncLastFitbitUserSleep(data, userId, date) - const lastSync: string = moment.utc().format() - this.updateLastSync(userId, lastSync) - .then(res => { - if (res) this.publishLastSync(userId, lastSync) - }).catch(err => this._logger.info(`Error at update the last sync: ${err.message}`)) - return Promise.resolve() - } catch (err) { - return Promise.reject(err) - } - } - public getTokenPayload(token: string): Promise { try { return Promise.resolve(jwt.decode(token)) @@ -317,129 +279,6 @@ export class FitbitDataRepository implements IFitbitDataRepository { } } - private syncLastFitbitUserWeight(data: FitbitAuthData, userId: string, date: string): Promise { - return new Promise((resolve, reject) => { - this.getUserBodyDataFromInterval(data.access_token!, date, date) - .then(async weights => { - if (weights && weights.length) { - const resources: Array = await this.filterDataAlreadySync(weights, ResourceDataType.BODY, userId) - - // Parse list of weights - const weightList: Array = this.parseWeightList(resources, userId) - if (weightList.length) { - // Publish list of weights - this._eventBus.bus.pubSyncWeight(weightList.map(item => item.toJSON())) - .then(() => { - this._logger.info(`Weight Measurements from ${userId} successful published!`) - this.saveResourceList(resources, userId) - .then(() => { - // If publish is successful, save the sync resources on database - this._logger.info(`Weight logs from ${userId} saved successful!`) - }) - .catch(err => { - this._logger.error(`Error at save weight: ${err.message}`) - }) - }) - .catch(err => this._logger.error(`Error at publish weight: ${err.message}`)) - } - } - return resolve() - }).catch(err => reject(err)) - }) - } - - private syncLastFitbitUserActivity(data: FitbitAuthData, userId: string, date: string): Promise { - return new Promise((resolve, reject) => { - this.getUserActivities(data.access_token!, 100, date) - .then(async activities => { - if (activities && activities.length) { - const resources: Array = - await this.filterDataAlreadySync(activities, ResourceDataType.ACTIVITIES, userId) - - // Parse list of activities - const activityList: Array = this.parsePhysicalActivityList(resources, userId) - if (activityList.length) { - // Publish list of activities - this._eventBus.bus.pubSyncPhysicalActivity(activityList.map(item => item.toJSON())) - .then(() => { - this._logger.info(`Physical activities from ${userId} successful published!`) - this.saveResourceList(resources, userId) - .then(() => { - // If publish is successful, save the sync resources on database - this._logger.info(`Physical activities from ${userId} saved successful!`) - }) - .catch(err => { - this._logger.error(`Error at save physical activities: ${err.message}`) - }) - }) - .catch(err => this._logger.error(`Error at publish physical activities: ${err.message}`)) - } - } - return resolve() - }).catch(err => reject(err)) - }) - } - - private async syncLastFitbitUserActivityLogs(data: FitbitAuthData, userId: string, date: string): Promise { - try { - const stepsLogs: Array = await this.syncUserActivitiesLogs(data, date, 'steps') - const caloriesLogs: Array = await this.syncUserActivitiesLogs(data, date, 'calories') - const minutesSedentaryLogs: Array = await this.syncUserActivitiesLogs(data, date, 'minutesSedentary') - const minutesLightlyActiveLogs: Array = await this.syncUserActivitiesLogs(data, date, 'minutesLightlyActive') - const minutesFairlyActiveLogs: Array = await this.syncUserActivitiesLogs(data, date, 'minutesFairlyActive') - const minutesVeryActiveLogs: Array = await this.syncUserActivitiesLogs(data, date, 'minutesVeryActive') - - const userLog: UserLog = await this.parseActivityLogs( - stepsLogs, - caloriesLogs, - minutesSedentaryLogs, - minutesLightlyActiveLogs, - this.mergeLogsValues(minutesFairlyActiveLogs, minutesVeryActiveLogs), - userId - ) - - this._eventBus.bus.pubSyncLog(userLog.toJSONList()) - .then(() => { - this._logger.info(`Activities logs from ${userId} successful published!`) - }) - .catch(err => this._logger.error(`Error at publish activities logs: ${err.message}`)) - return Promise.resolve() - } catch (err) { - return Promise.reject(err) - } - } - - private syncLastFitbitUserSleep(data: FitbitAuthData, userId: string, date: string): Promise { - return new Promise((resolve, reject) => { - this.getUserSleepFromInterval(data.access_token!, date, date) - .then(async sleeps => { - if (sleeps && sleeps.length) { - const resources: Array = await this.filterDataAlreadySync(sleeps, ResourceDataType.SLEEP, userId) - - // Parse list of sleep - const sleepList: Array = this.parseSleepList(resources, userId) - if (sleepList.length) { - // Publish list of sleep. - this._eventBus.bus.pubSyncSleep(sleepList.map(item => item.toJSON())) - .then(() => { - this._logger.info(`Sleep from ${userId} successful published!`) - this.saveResourceList(resources, userId) - .then(() => { - // If publish is successful, save the sync resources on database - this._logger.info(`Sleep logs from ${userId} saved successful!`) - }) - .catch(err => { - this._logger.error(`Error at save sleep: ${err.message}`) - }) - }) - .catch(err => this._logger.error(`Error at publish sleep: ${err.message}`)) - } - } - return resolve() - }).catch(err => reject(err)) - }) - } - private saveResourceList(resources: Array, userId: string): Promise> { return new Promise>(async (resolve, reject) => { const result: Array = [] @@ -521,7 +360,7 @@ export class FitbitDataRepository implements IFitbitDataRepository { moment(data.last_sync).format('YYYY-MM-DD') ) } - return this.getLastUserActivities(data.access_token!) + return this.getUserActivities(data.access_token!, 100, moment().format('YYYY-MM-DD')) } private async syncUserActivitiesLogs(data: FitbitAuthData, lastSync: string, resource: string): Promise> { @@ -552,15 +391,6 @@ export class FitbitDataRepository implements IFitbitDataRepository { }) } - private async getUserSleepFromInterval(token: string, baseDate: string, endDate: string): Promise { - const path: string = `/sleep/date/${baseDate}/${endDate}.json` - return new Promise((resolve, reject) => { - this._fitbitClientRepo.getDataFromPath(path, token) - .then(result => resolve(result.sleep)) - .catch(err => reject(this.fitbitClientErrorListener(err, token))) - }) - } - private async getUserActivityLogs(token: string, resource: string, baseDate: string, endDate: string): Promise { return new Promise((resolve, reject) => { return this._fitbitClientRepo @@ -579,16 +409,6 @@ export class FitbitDataRepository implements IFitbitDataRepository { }) } - private async getLastUserActivities(token: string): Promise { - const now: string = moment().add(1, 'day').format('YYYY-MM-DD') - const path: string = `/activities/list.json?beforeDate=${now}&sort=desc&offset=0&limit=100` - return new Promise((resolve, reject) => { - this._fitbitClientRepo.getDataFromPath(path, token) - .then(result => resolve(result.activities)) - .catch(err => reject(this.fitbitClientErrorListener(err, token))) - }) - } - private async getUserActivities(token: string, limit: number, afterDate: string): Promise { const path: string = `/activities/list.json?afterDate=${afterDate}&sort=desc&offset=0&limit=${limit}` return new Promise((resolve, reject) => { diff --git a/src/ui/controllers/fitbit.subscriber.controller.ts b/src/ui/controllers/fitbit.subscriber.controller.ts deleted file mode 100644 index b508153..0000000 --- a/src/ui/controllers/fitbit.subscriber.controller.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { controller, httpGet, httpPost, request, response } from 'inversify-express-utils' -import { Request, Response } from 'express' -import HttpStatus from 'http-status-codes' -import { inject } from 'inversify' -import { Identifier } from '../../di/identifiers' -import { IUserAuthDataService } from '../../application/port/user.auth.data.service.interface' -import { ILogger } from '../../utils/custom.logger' - -@controller('/v1/fitbit/subscriber') -export class FitbitSubscriberController { - constructor( - @inject(Identifier.USER_AUTH_DATA_SERVICE) private readonly _userAuthDataService: IUserAuthDataService, - @inject(Identifier.LOGGER) private readonly _logger: ILogger - ) { - } - - @httpGet('/') - public async verifySubscriberDefault(@request() req: Request, @response() res: Response): Promise { - return req.query.filters.verify && req.query.filters.verify === `${process.env.FITBIT_CLIENT_SUBSCRIBER}` ? - res.status(HttpStatus.NO_CONTENT).send() : res.status(HttpStatus.NOT_FOUND).send() - } - - @httpPost('/') - public async getInfo(@request() req: Request, @response() res: Response): Promise { - this._logger.info(`Prepare to sync ${req.body[0].collectionType} from ${req.body[0].ownerId}.`) - this._userAuthDataService.syncLastFitbitUserData(req.body[0].ownerId, req.body[0].collectionType, req.body[0].date).then() - return res.status(200).send() - } -} diff --git a/test/integration/routes/fitbit.subscriber.controller.spec.ts b/test/integration/routes/fitbit.subscriber.controller.spec.ts deleted file mode 100644 index bbf6ac9..0000000 --- a/test/integration/routes/fitbit.subscriber.controller.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { Identifier } from '../../../src/di/identifiers' -import { App } from '../../../src/app' -import { expect } from 'chai' -import { DIContainer } from '../../../src/di/di' - -const app: App = DIContainer.get(Identifier.APP) -const request = require('supertest')(app.getExpress()) - -describe('Routes: FitbitSubscriber', () => { - describe('GET /v1/fitbit/subscriber', () => { - context('when validate fitbit client subscriber', () => { - it('should return status code 204 and no content', () => { - return request - .get(`/v1/fitbit/subscriber?verify=${process.env.FITBIT_CLIENT_SUBSCRIBER}`) - .set('Content-Type', 'application/json') - .expect(204) - .then(res => { - expect(res.body).to.eql({}) - }) - }) - }) - context('when the verification fails', () => { - it('should return status code 404 and no content', () => { - return request - .get('/v1/fitbit/subscriber?verify=invalid') - .set('Content-Type', 'application/json') - .expect(404) - .then(res => { - expect(res.body).to.eql({}) - }) - }) - }) - }) - describe('POST /v1/fitbit/subscriber', () => { - context('when the client receive a subscribe notification', () => { - it('should return status code 200 and no content', () => { - return request - .post('/v1/fitbit/subscriber') - .send([{ - ownerId: '1A2B3', - collectionType: 'body', - date: '2019-09-18' - }]) - .set('Content-Type', 'application/json') - .expect(200) - .then(res => { - expect(res.body).to.eql({}) - }) - }) - }) - }) -}) diff --git a/test/unit/repositories/fitbit.data.repository.spec.ts b/test/unit/repositories/fitbit.data.repository.spec.ts index 3fbd2db..32c246f 100644 --- a/test/unit/repositories/fitbit.data.repository.spec.ts +++ b/test/unit/repositories/fitbit.data.repository.spec.ts @@ -105,44 +105,6 @@ describe('Repositories: FitbitDataRepository', () => { }) }) - describe('subscribeUserEvent()', () => { - context('when subscribe in a specific event', () => { - it('should return undefined', () => { - return repo.subscribeUserEvent(data.fitbit!, 'activities', 'ACTIVITIES') - .then(res => { - assert.isUndefined(res) - }) - }) - }) - context('when a error occurs', () => { - it('should reject an error', () => { - return repo.subscribeUserEvent(data.fitbit!, 'error', 'ACTIVITIES') - .catch(err => { - assert.propertyVal(err, 'message', 'An error occurs!') - }) - }) - }) - }) - - describe('unsubscribeUserEvent()', () => { - context('when unsubscribe in a specific event', () => { - it('should return undefined', () => { - return repo.unsubscribeUserEvent(data.fitbit!, 'activities', 'ACTIVITIES') - .then(res => { - assert.isUndefined(res) - }) - }) - }) - context('when a error occurs', () => { - it('should reject an error', () => { - return repo.unsubscribeUserEvent(data.fitbit!, 'error', 'ACTIVITIES') - .catch(err => { - assert.propertyVal(err, 'message', 'An error occurs!') - }) - }) - }) - }) - describe('updateLastSync()', () => { context('when update the last data sync', () => { it('should return true', () => { diff --git a/test/unit/services/user.auth.data.service.spec.ts b/test/unit/services/user.auth.data.service.spec.ts index d6ca250..9968ff4 100644 --- a/test/unit/services/user.auth.data.service.spec.ts +++ b/test/unit/services/user.auth.data.service.spec.ts @@ -7,7 +7,6 @@ import { IUserAuthDataService } from '../../../src/application/port/user.auth.da import { assert } from 'chai' import { FitbitAuthData } from '../../../src/application/domain/model/fitbit.auth.data' import { Query } from '../../../src/infrastructure/repository/query/query' -import moment = require('moment') import { CustomLoggerMock } from '../../mocks/custom.logger.mock' import { EventBusRabbitMQMock } from '../../mocks/eventbus/eventbus.rabbitmq.mock' import { DataSync } from '../../../src/application/domain/model/data.sync' @@ -208,15 +207,4 @@ describe('Services: UserAuthDataService', () => { }) }) }) - describe('syncLastFitbitUserData()', () => { - context('when user does not exists', () => { - it('should return undefined', () => { - return service - .syncLastFitbitUserData('XXYYXX', 'weight', moment().format('YYYY-MM-DD')) - .then(res => { - assert.isUndefined(res) - }) - }) - }) - }) })