feedbaby-client
Version:
Client for the FeedBaby App
194 lines (193 loc) • 9.07 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const url = __importStar(require("url"));
const form_data_1 = __importDefault(require("form-data"));
const defaultAndroidHttpClientFactory_1 = require("./defaults/defaultAndroidHttpClientFactory");
const defaultAppDataZipCreator_1 = require("./defaults/defaultAppDataZipCreator");
const defaultAppDataZipReader_1 = require("./defaults/defaultAppDataZipReader");
const uuid_1 = require("uuid");
const AuthParameters_1 = require("./parameters/AuthParameters");
const DeviceParameters_1 = require("./parameters/DeviceParameters");
const BaseParameters_1 = require("./parameters/BaseParameters");
const SyncParameters_1 = require("./parameters/SyncParameters");
class Device {
constructor(id) {
this.id = id;
}
static create() {
return new Device(`${Date.now()}-${uuid_1.v4()}`);
}
}
exports.Device = Device;
class FeedBabyClient {
constructor(host = FeedBabyClient.HOST, httpClientFactory = defaultAndroidHttpClientFactory_1.defaultAndroidHttpClientFactory, appDataCreator = defaultAppDataZipCreator_1.defaultAppDataZipCreator(), appDataReader = defaultAppDataZipReader_1.defaultAppDataZipReader()) {
this.host = host;
this.httpClientFactory = httpClientFactory;
this.appDataCreator = appDataCreator;
this.appDataReader = appDataReader;
this.baseParameters = new BaseParameters_1.BaseParameters();
this.syncParameters = new SyncParameters_1.SyncParameters();
this.authParameters = new AuthParameters_1.AuthParameters();
this.deviceParameters = new DeviceParameters_1.DeviceParameters();
this.client = httpClientFactory(url.resolve(host, FeedBabyClient.BASE_PATH));
}
ping() {
return __awaiter(this, void 0, void 0, function* () {
let pingMessage = "";
try {
const response = yield this.client.get(FeedBabyClient.PING_ENDPOINT, { params: this.baseParameters.create() });
pingMessage = response.data;
}
catch (error) {
console.error("Ping failed", { error });
}
return (pingMessage === "success");
});
}
/**
* Determines the latest 'version' synchronisation, which is just a unix timestamp of the last sync.
*
* Contrary to what I thought this is not the same date returned in the Date header of the merge.
*/
checkVersion(authentication) {
return __awaiter(this, void 0, void 0, function* () {
this.authParameters.validate(authentication);
const params = Object.assign(Object.assign(Object.assign({}, this.baseParameters.create()), this.authParameters.create(authentication)), this.syncParameters.create());
const { data } = yield this.client.get(FeedBabyClient.CHECK_VERSION_ENDPOINT, { params });
try {
return {
version: `${data}`,
dateOfLastSync: new Date(data)
};
}
catch (err) {
throw new Error(`API replied with value that is not a date: ${data}`);
}
});
}
registerDevice(auth, device, deviceToken) {
return __awaiter(this, void 0, void 0, function* () {
this.authParameters.validate(auth);
this.deviceParameters.validate(device);
const params = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.baseParameters.create()), this.syncParameters.create()), this.authParameters.create(auth)), this.deviceParameters.create(device)), { deviceToken });
const response = yield this.client.get(FeedBabyClient.REGISTER_DEVICE_TOKEN_ENDPOINT, { params });
return response.data;
});
}
/**
* WARNING: This method is destructive!
*
* The first time a new device syncs with the server no data will be erased from the server, only added. What is
* returned is all the data that the server has of the passphrase + date combination.
*
* Subsequent syncs for a device the server knows could result in data being erased from the account. i.e. if the
* ZIP from the device doesn't contain data that the server knows it previously sent to the device, then the server
* will assume the user of the device deleted this data, thus update the data on the server accordingly.
*
* @return Returns the merged sync
*/
merge(auth, device, zip) {
return __awaiter(this, void 0, void 0, function* () {
this.authParameters.validate(auth);
this.deviceParameters.validate(device);
if (!zip) {
zip = this.createZipFromAppFirstStart();
}
const responseZip = yield this.mergeZip(auth, device, zip);
return this.appDataReader.read(responseZip);
});
}
mergeZip(auth, device, zip) {
return __awaiter(this, void 0, void 0, function* () {
const params = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.baseParameters.create()), this.syncParameters.create()), this.authParameters.create(auth)), this.deviceParameters.create(device)), { "lastSyncFinishedStatus": "FINISHED" });
const form = new form_data_1.default();
form.append("newZip", zip, {
contentType: "application/zip",
filename: 'newZip'
});
const formHeaders = form.getHeaders();
try {
const response = yield this.client.post(FeedBabyClient.MERGE_ENDPOINT, form, {
responseType: 'arraybuffer',
params,
headers: Object.assign(Object.assign({}, formHeaders), { "Accept-Encoding": "gzip" }),
});
return response.data;
}
catch (error) {
console.log(error);
throw error;
}
});
}
createZipFromAppFirstStart() {
return this.appDataCreator.create({
babies: [{
id: "1",
name: "",
birthDate: "2019-06-19 00:00:00",
babyType: "PRIMARY",
gender: "MALE"
}],
babyDateOfBirth: [
{
"id": "2",
"day_of_the_month": "19",
"month_of_the_year": "6",
"year": "2019"
}
],
babyImages: [],
excretionNotificationTriggers: [],
excretions: [],
feeds: [],
growths: [],
journalEntries: [],
medicineRecords: [],
medicines: [],
pauses: [],
pumpingNotificationTriggers: [],
pumpingTimeOfDayNotificationTriggers: [],
pumpings: [],
sleepingNotificationTriggers: [],
sleepingsTimeOfDayNotificationTriggers: [],
sleeps: [],
teeths: [],
temperatures: [],
vaccinations: [],
excretionTimeOfDayNotificationTriggers: [],
feedingNotificationTriggers: [],
feedingTimeOfDayNotificationTriggers: [],
generalNotesNotificationTriggers: [],
generalNotesTimeOfDayNotificationTriggers: [],
medicationRecordsNotificationTriggers: [],
medicationRecordsTimeOfDayNotificationTriggers: []
});
}
}
exports.FeedBabyClient = FeedBabyClient;
FeedBabyClient.HOST = "http://www.feedbaby.com.au/";
FeedBabyClient.BASE_PATH = "feedbabysync_v12";
FeedBabyClient.PING_ENDPOINT = "/ping";
FeedBabyClient.CHECK_VERSION_ENDPOINT = "/checkversion";
FeedBabyClient.MERGE_ENDPOINT = "/merge";
FeedBabyClient.REGISTER_DEVICE_TOKEN_ENDPOINT = "/registerDeviceToken";