Skip to content

Commit 841fe7a

Browse files
committed
initial commit
1 parent 5509337 commit 841fe7a

File tree

7 files changed

+514
-1
lines changed

7 files changed

+514
-1
lines changed

.gitignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
.DS_Store
2+
.idea
3+
.env
4+
node_modules
5+
yarn-error.log
6+
npm-debug.log

README.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
1-
# segment-api
1+
# Segment Api
2+
3+
## Example
4+
5+
```javascript
6+
const segmentApi = new SegmentApi({
7+
WORKSPACE: 'workspaceId',
8+
TOKEN: 'token', // personal access token
9+
});
10+
11+
const response = await segmentApi.getCatalogDestination({name: 'facebook-pixel'});
12+
13+
```

lib/index.js

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const axios = require('axios');
2+
const _ = require('lodash');
3+
const methodMap = require('./methods');
4+
const API_METHODS = require('./request-type');
5+
6+
const BASE_URL = 'https://platform.segmentapis.com/v1beta';
7+
8+
/**
9+
* @class SegmentApi
10+
* @method login
11+
*/
12+
class SegmentApi {
13+
/**
14+
*
15+
* @param config
16+
* @param config.WORKSPACE
17+
* @param [config.BASE_URL]
18+
* @param [config.TOKEN]
19+
* @param [config.CATALOG_SOURCE]
20+
* @param [config.CONNECTION_MODE]
21+
* @param [config.transformApiConfig]
22+
*/
23+
constructor(config) {
24+
this.__axios = axios.create({
25+
baseURL: config.BASE_URL || BASE_URL,
26+
});
27+
28+
this.WORKSPACE = config.WORKSPACE;
29+
this.CATALOG_SOURCE = config.CATALOG_SOURCE || 'catalog/sources/javascript';
30+
this.CONNECTION_MODE = config.CONNECTION_MODE || 'CLOUD';
31+
this.TOKEN = config.TOKEN;
32+
this.transformApiConfig = config.transformApiConfig || this.transformConfig;
33+
34+
this.applyMethods(methodMap);
35+
};
36+
37+
/**
38+
*
39+
* @param methodMap
40+
*/
41+
applyMethods(methodMap) {
42+
Object.keys(methodMap)
43+
.forEach((methodName) => {
44+
this[methodName] = (...rest) => {
45+
if (!rest.length) {
46+
rest = [{}];
47+
}
48+
const config = methodMap[methodName].call(this, ...rest);
49+
50+
return this.callAPI(config);
51+
};
52+
});
53+
}
54+
55+
async axios(config) {
56+
return this.__axios(this.transformApiConfig(config));
57+
}
58+
59+
callAPI({method, url, data, headers = {}, ...rest}) {
60+
const requestHeaders = _.clone(headers);
61+
if (url.indexOf('access-tokens') === -1 && !!this.TOKEN &&
62+
!requestHeaders.Authorization) {
63+
requestHeaders.Authorization = `Bearer ${this.TOKEN}`;
64+
}
65+
66+
let requestData = {data};
67+
if (method === API_METHODS.GET) {
68+
requestData = {params: data};
69+
}
70+
71+
const config = {
72+
...rest,
73+
...requestData,
74+
method,
75+
headers: requestHeaders,
76+
url,
77+
};
78+
79+
return this.axios(config);
80+
}
81+
82+
transformConfig(config) {
83+
return config;
84+
}
85+
86+
}
87+
88+
module.exports = SegmentApi;

0 commit comments

Comments
 (0)