up-bank-typescript
Version:
Typescript wrapper for Up Bank API
491 lines (450 loc) • 18 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var fetch = require('node-fetch');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(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());
});
}
class Fetch {
constructor(baseUrl, bearerToken) {
this.baseUrl = baseUrl;
this.headers = new fetch.Headers({
Authorization: `Bearer ${bearerToken}`,
});
}
get(path) {
return __awaiter(this, void 0, void 0, function* () {
const options = {
method: 'GET',
headers: this.headers,
};
const url = `${this.baseUrl}/${path}`;
return yield fetch__default['default'](url, options);
});
}
post(path, payload) {
return __awaiter(this, void 0, void 0, function* () {
const headers = new fetch.Headers(this.headers);
headers.set('Content-Type', 'application/json');
const options = {
method: 'POST',
body: JSON.stringify({
data: payload,
}),
headers,
};
const url = `${this.baseUrl}/${path}`;
return yield fetch__default['default'](url, options);
});
}
delete(path, payload) {
return __awaiter(this, void 0, void 0, function* () {
const options = {
method: 'DELETE',
body: JSON.stringify({
data: payload,
}),
headers: this.headers,
};
const url = `${this.baseUrl}/${path}`;
return yield fetch__default['default'](url, options);
});
}
}
var ResourceType;
(function (ResourceType) {
ResourceType["ACCOUNTS"] = "accounts";
ResourceType["CATEGORIES"] = "categories";
ResourceType["TAGS"] = "tags";
ResourceType["TRANSACTIONS"] = "transactions";
ResourceType["WEBHOOK"] = "webhook";
ResourceType["WEBHOOK_EVENTS"] = "webhook-events";
ResourceType["WEBHOOK_DELIVERY_LOGS"] = "webhook-delivery-logs";
})(ResourceType || (ResourceType = {}));
var Endpoint;
(function (Endpoint) {
Endpoint["ACCOUNTS"] = "accounts";
Endpoint["CATEGORIES"] = "categories";
Endpoint["TAGS"] = "tags";
Endpoint["TRANSACTIONS"] = "transactions";
Endpoint["UTIL"] = "util";
Endpoint["WEBHOOKS"] = "webhooks";
})(Endpoint || (Endpoint = {}));
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function stringifyPrimitive(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
}
function stringify (obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
}
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
function parse(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
}var querystring = {
encode: stringify,
stringify: stringify,
decode: parse,
parse: parse
};
const createQuerystring = (filters, size) => {
const query = {};
Object.entries(filters).forEach((key, value) => {
query[`filter[${key}]`] = value;
});
if (size) {
query['page[size]'] = size;
}
return querystring.stringify(query);
};
/**
* Accounts represent the underlying store used to track balances and the
* transactions that have occurred to modify those balances over time. Up
* currently has two types of account: SAVER—used to earn interest and to
* hit savings goals, and TRANSACTIONAL—used for everyday spending.
*/
class Accounts {
constructor(fetch) {
this.fetch = fetch;
}
/**
* Retrieve a paginated list of all accounts for the currently authenticated
* user. The returned list is paginated and can be scrolled by following the
* prev and next links where present.
* @param size The number of records to return in each page.
*/
list(size) {
return __awaiter(this, void 0, void 0, function* () {
const query = createQuerystring({}, size);
const response = yield this.fetch.get(`${Endpoint.ACCOUNTS}?${query}`);
return yield response.json();
});
}
/**
* Retrieve a specific account by providing its unique identifier.
* @param id The unique identifier for the account.
*/
get(id) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.get(`${Endpoint.ACCOUNTS}/${id}`);
return yield response.json();
});
}
/**
*
* @param account Retrieve a list of all transactions for a specific account.
* The returned list is paginated and can be scrolled by following the next
* and prev links where present. To narrow the results to a specific date
* range pass one or both of filter[since] and filter[until] in the query
* string. These filter parameters should not be used for pagination. Results
* are ordered newest first to oldest last.
* @param params
*/
transactions(account, params) {
return __awaiter(this, void 0, void 0, function* () {
const { size } = params, filters = __rest(params, ["size"]);
const query = createQuerystring(filters, size);
const response = yield this.fetch.get(`${Endpoint.ACCOUNTS}/${account}/${Endpoint.TRANSACTIONS}?${query}`);
return yield response.json();
});
}
}
/**
* Categories enable understanding where your money goes by driving powerful
* insights in Up. All categories in Up are pre-defined and are automatically
* assigned to new purchases in most cases. A parent-child relationship is used
* to represent categories, however parent categories cannot be directly
* assigned to transactions.
*/
class Categories {
constructor(fetch) {
this.fetch = fetch;
}
/**
* Retrieve a list of all categories and their ancestry.
* The returned list is not paginated.
* @param parent The unique identifier of a parent category for which to return only its children. Providing an invalid category identifier results in a 404 response.
*/
list(parent) {
return __awaiter(this, void 0, void 0, function* () {
const query = createQuerystring({ parent });
const response = yield this.fetch.get(`${Endpoint.CATEGORIES}?${query}`);
return yield response.json();
});
}
/**
* Retrieve a specific category by providing its unique identifier.
* @param id The unique identifier for the category.
*/
get(id) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.get(`${Endpoint.CATEGORIES}/${id}`);
return yield response.json();
});
}
}
/**
* Tags are custom labels that can be associated with transactions on Up.
* Within the Up application, tags provide additional insight into spending.
* For example, you could have a "Take Away" tag that you apply to purchases
* from food delivery services. The Up API allows you to manage the tags
* associated with transactions. Each transaction may have up to 6 tags.
*
* Tags are identified by their labels, which are unique strings, so the tag
* "Holiday" has also the id "Holiday".
*/
class Tags {
constructor(fetch) {
this.fetch = fetch;
}
/**
* Retrieve a list of all tags currently in use. The returned list is paginated
* and can be scrolled by following the next and prev links where present.
* Results are ordered lexicographically. The transactions relationship for
* each tag exposes a link to get the transactions with the given tag.
* @param size The number of records to return in each page.
*/
list(size) {
return __awaiter(this, void 0, void 0, function* () {
const query = createQuerystring({}, size);
const response = yield this.fetch.get(`${Endpoint.TAGS}?${query}`);
return yield response.json();
});
}
}
/**
* Transactions represent the movement of money into and out of an account.
* They have many characteristics that vary depending on the kind of
* transaction. Transactions may be temporarily HELD (pending) or SETTLED,
* typically depending on which payment method was used at the point of sale.
*/
class Transactions {
constructor(fetch) {
this.fetch = fetch;
}
/**
* Retrieve a list of all transactions across all accounts for the currently
* authenticated user. The returned list is paginated and can be scrolled by
* following the next and prev links where present. To narrow the results to
* a specific date range pass one or both of filter[since] and filter[until]
* in the query string. These filter parameters should not be used for
* pagination. Results are ordered newest first to oldest last.
* @param params
*/
list(params) {
return __awaiter(this, void 0, void 0, function* () {
const { size } = params, filters = __rest(params, ["size"]);
const query = createQuerystring(filters, size);
const response = yield this.fetch.get(`/${Endpoint.TRANSACTIONS}?${query}`);
return yield response.json();
});
}
/**
* Retrieve a specific transaction by providing its unique identifier.
* @param id The unique identifier for the transaction.
*/
get(id) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.get(`${Endpoint.TRANSACTIONS}/${id}`);
return yield response.json();
});
}
/**
* Associates one or more tags with a specific transaction. No more than 6
* tags may be present on any single transaction. Duplicate tags are silently
* ignored. An HTTP 204 is returned on success. The associated tags, along
* with this request URL, are also exposed via the tags relationship on the
* transaction resource returned from /transactions/{id}.
* @param transaction The unique identifier for the transaction.
* @param tags The tags to remove from the transaction.
*/
addTags(transaction, tags) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.post(`${Endpoint.TRANSACTIONS}/${transaction}/relationships/${Endpoint.TAGS}`, tags);
return response.ok;
});
}
/**
* Disassociates one or more tags from a specific transaction. Tags that are
* not associated are silently ignored. An HTTP 204 is returned on success.
* The associated tags, along with this request URL, are also exposed via the
* tags relationship on the transaction resource returned from /transactions/{id}.
* @param transaction The unique identifier for the transaction.
* @param tags The tags to remove from the transaction.
*/
removeTags(transaction, tags) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.delete(`${Endpoint.TRANSACTIONS}/${transaction}/relationships/${Endpoint.TAGS}`, tags);
return response.ok;
});
}
}
/**
* Some endpoints exist not to expose data, but to test the API itself.
* Currently there is only one endpoint in this group: ping!
*/
class Util {
constructor(fetch) {
this.fetch = fetch;
}
/**
* Make a basic ping request to the API. This is useful to verify that
* authentication is functioning correctly. On authentication success an HTTP
* 200 status is returned. On failure an HTTP 401 error response is returned.
*/
ping() {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.fetch.get(`${Endpoint.UTIL}/ping`);
return yield response.json();
});
}
}
const baseUrl = 'https://api.up.com.au/api/v1';
class Up {
constructor(apiKey) {
this.fetch = new Fetch(baseUrl, apiKey);
this.accounts = new Accounts(this.fetch);
this.categories = new Categories(this.fetch);
this.tags = new Tags(this.fetch);
this.transactions = new Transactions(this.fetch);
this.util = new Util(this.fetch);
}
}
exports.Up = Up;