Skip to content
This repository has been archived by the owner on Jul 9, 2023. It is now read-only.

feature: setup Node.js API client #1

Merged
merged 6 commits into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENCE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022 Lovro Colic

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.
71 changes: 69 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,75 @@ This is a Node.js wrapper for Lago API

## Installation

TODO...
Install the lago-nodejs-client via npm:

$ npm install lago-nodejs-client


## Usage

TODO...
``` javascript
import Client from 'lago-nodejs-client'

let client = new Client('api_key')
```

### Events
[Api reference](https://doc.getlago.com/docs/api/events)

``` javascript
import Event from 'lago-nodejs-client/event'

let event = new Event(
"5eb02857-a71e-4ea2-bcf9-57d8885990ba", // customerId
"__UNIQUE_TRANSACTION_ID__", // transactionId
"code", // code
1650893379, // timestamp
{custom_field: "custom"} // properties
)

await client.createEvent(event);
```

### Customers
[Api reference](https://doc.getlago.com/docs/api/customers/customer-object)

``` javascript
import Customer from 'lago-nodejs-client/customer'

let customer = new Customer(
"5eb02857-a71e-4ea2-bcf9-57d8885990ba", // customerId
None, // addressLine1
None, // addressLine2
None, // city
None, // country
"[email protected]", // email
None, // legalName
None, // legalNumber
None, // lagoUrl
"test name", // name
None, // phone
None, // state
None, // url
None, // vatRate
None // zipcode
)
await client.createCustomer(customer);
```

### Subscriptions
[Api reference](https://doc.getlago.com/docs/api/subscriptions/subscription-object)

``` javascript
import Subscription from 'lago-nodejs-client/subscription'

let subscription = new Subscription(
"5eb02857-a71e-4ea2-bcf9-57d8885990ba", // customerId
"code" // planCode
)
await client.createSubscription(subscription);
await client.deleteSubscription({
customerId: "5eb02857-a71e-4ea2-bcf9-57d8885990ba"
})
```

111 changes: 111 additions & 0 deletions lib/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import fetch from 'node-fetch';

export default class Client {
BASE_URL = 'https://api.getlago.com';
API_PATH = '/api/v1'

constructor(apiKey, apiUrl) {
this.apiKey = apiKey;
this.baseUrl = apiUrl || this.BASE_URL;
}

headers = function(method = 'get') {
let bearer = `Bearer ${this.apiKey}`;
let headers;

if (method == 'post' || 'delete') {
headers =
{
'Content-Type': 'application/json',
'Authorization': bearer
}
} else {
headers =
{
'Authorization': bearer
}
}

return headers;
}

async apiRequest(path, method, body = null) {
let fullUrl = `${this.baseUrl}${this.API_PATH}${path}`;
let requestHeaders = this.headers(method)
let options = {
method: method,
headers: requestHeaders
}

if (method === 'post' || method === 'delete') {
options.body = JSON.stringify(body)
}

let data;
await fetch(fullUrl, options).then(response => {
if (response.ok) {
if (method === 'get') {
data = response.text();
}
else if (method === 'post' && response.body._readableState.length === 0) {
data = true;
} else {
data = response.json();
}
} else {
throw new LagoApiError(`The HTTP status of the response: ${response.status}, URL: ${fullUrl}`);
}
});
return data;
}

////////////// CLIENT METHODS ///////////

async createEvent(inputEvent){
let response;
await this.apiRequest(`/events`, 'post', inputEvent.wrapAttributes())
.then(res => response = res);

return response;
}

async createCustomer(inputCustomer){
let response;
await this.apiRequest(`/customers`, 'post', inputCustomer.wrapAttributes())
.then(res => response = res.customer);

return response;
}

async createSubscription(inputSubscription){
let response;
await this.apiRequest(`/subscriptions`, 'post', inputSubscription.wrapAttributes())
.then(res => response = res.subscription);

return response;
}

async deleteSubscription(input){
let body = {
customer_id: input.customerId || null
}

let response;
await this.apiRequest(`/subscriptions`, 'delete', body)
.then(res => response = res.subscription);

return response;
}

async webhookPublicKey(){
let response;
await this.apiRequest(`/webhooks/public_key`, 'get').then(res => response = res);

let buff = new Buffer(response, 'base64');
let key = buff.toString('ascii');

return key;
}
}

class LagoApiError extends Error {}
59 changes: 59 additions & 0 deletions lib/models/customer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
export default class Customer {
constructor(
customerId,
name,
addressLine1 = null,
addressLine2 = null,
city = null,
country = null,
email = null,
legalName = null,
legalNumber = null,
logoUrl = null,
phone = null,
state = null,
url = null,
vatRate = null,
zipcode = null
) {
this.customerId = customerId,
this.name = name,
this.addressLine1 = addressLine1,
this.addressLine2 = addressLine2,
this.city = city,
this.country = country,
this.email = email,
this.legalName = legalName,
this.legalNumber = legalNumber,
this.logoUrl = logoUrl,
this.phone = phone,
this.state = state,
this.url = url,
this.vatRate = vatRate,
this.zipcode = zipcode
}

wrapAttributes = function () {
let result = {
customer: {
customer_id: this.customerId,
name: this.name,
address_line1: this.addressLine1,
address_line2: this.addressLine2,
city: this.city,
country: this.country,
email: this.email,
legal_name: this.legalName,
legal_number: this.legalNumber,
logo_url: this.logoUrl,
phone: this.phone,
state: this.state,
url: this.url,
vat_rate: this.vatRate,
zipcode: this.zipcode
}
};

return result;
}
}
23 changes: 23 additions & 0 deletions lib/models/event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export default class Event {
constructor(transactionId, customerId, code, timestamp = null, properties = null) {
this.transactionId = transactionId,
this.customerId = customerId,
this.code = code,
this.timestamp = timestamp,
this.properties = properties
}

wrapAttributes = function () {
let result = {
event: {
transaction_id: this.transactionId,
customer_id: this.customerId,
code: this.code,
timestamp: this.timestamp,
properties: this.properties
}
};

return result;
}
}
17 changes: 17 additions & 0 deletions lib/models/subscription.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export default class Subscription {
constructor(customerId, planCode) {
this.customerId = customerId,
this.planCode = planCode
}

wrapAttributes = function () {
let result = {
subscription: {
customer_id: this.customerId,
plan_code: this.planCode
}
};

return result;
}
}
Loading