@apolitical/sdk 0.0.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.gitlab-ci.yml ADDED
@@ -0,0 +1,25 @@
1
+ # External jobs
2
+ include:
3
+ - project: 'apolitical/templates/gitlab-pipelines'
4
+ ref: master
5
+ file: 'Node-Testing.gitlab-ci.yml'
6
+
7
+ stages:
8
+ - cache
9
+ - test
10
+ - publish
11
+
12
+ # Publish jobs
13
+
14
+ publish-module:
15
+ stage: publish
16
+ image: node:12.20.1-alpine3.11
17
+ extends: .yarn-install
18
+ only:
19
+ - tags
20
+ - /^v\d+\.\d+\.\d+$/
21
+ before_script:
22
+ - yarn build
23
+ script:
24
+ - echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > ~/.npmrc
25
+ - yarn publish --access=public
@@ -0,0 +1,8 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+
4
+ yarn lint-format
5
+
6
+ yarn build
7
+
8
+ yarn test
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.0.1] - 2021-01-18
9
+ ### Added
10
+ - Initial setup
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # Apolitical SDK
2
+
3
+ Browser library to interact with Apolitical's APIs
4
+
5
+ ## Requirements
6
+
7
+ Requires the following to run:
8
+
9
+ - [node.js][node] 12.20.1+
10
+ - [yarn][yarn]
11
+
12
+ [node]: https://nodejs.org/en/download/
13
+ [yarn]: https://classic.yarnpkg.com/en/docs/install
14
+
15
+ ## Installation
16
+
17
+ Install with `yarn`:
18
+
19
+ ```sh
20
+ yarn add @apolitical/sdk
21
+ ```
22
+
23
+ ## Available Scripts
24
+
25
+ In the project directory, you can run:
26
+ ### `yarn run test`
27
+
28
+ Runs the test (and the interactive mode can be enabled with `--watchAll`).
29
+
30
+ ### `yarn build`
31
+
32
+ Builds the library for production to the `build` folder.
33
+ It correctly bundles the code on production mode and optimizes the build for the best performance.
34
+
35
+ ### `yarn publish`
36
+
37
+ Publishes the library to NPM.
38
+
39
+ ## Usage
40
+
41
+ The recommended way to use `@apolitical/sdk` is to use the provided functionality:
42
+
43
+ ```js
44
+ const { ping } = require('@apolitical/sdk');
45
+
46
+ const result = ping();
47
+ console.log(result);
48
+ ```
package/build/index.js ADDED
@@ -0,0 +1 @@
1
+ !function(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r(require("axios"),require("@apolitical/error-reporting")):"function"==typeof define&&define.amd?define(["axios","@apolitical/error-reporting"],r):"object"==typeof exports?exports.ApoliticalSDK=r(require("axios"),require("@apolitical/error-reporting")):e.ApoliticalSDK=r(e.axios,e["@apolitical/error-reporting"])}(this,(function(e,r){return function(){"use strict";var t={30:function(e){e.exports=r},300:function(r){r.exports=e}},o={};function n(e){var r=o[e];if(void 0!==r)return r.exports;var i=o[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,{a:r}),r},n.d=function(e,r){for(var t in r)n.o(r,t)&&!n.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},n.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return function(){n.r(i),n.d(i,{default:function(){return c}});var e=n(300),r=n.n(e),t=n(30);const{APIS:{BACKEND_TEMPLATE:{BASE_URL:o,ENDPOINTS:{DUMMY:a}}}}={APIS:{BACKEND_TEMPLATE:{BASE_URL:"/api/backend-template",ENDPOINTS:{DUMMY:"/dummy"}}}};var c={setContext:({origin:e,gcpErrorsApiKey:r,serviceName:o})=>{(0,t.setContext)({origin:e,accessToken:r,serviceName:o})},template:{ping:async()=>{let e=null;try{({data:e}=await r().get(`${o}${a}`))}catch(e){(async e=>{let r="Error at Apolitical SDK: ";e.response?r+=JSON.stringify(e.response):e.request?r+=JSON.stringify(e.request):r+=e.message,console.warn(r);try{await(0,t.reportError)(new Error(r))}catch(e){console.warn(`Cannot report error: ${e.message}`)}})(e)}return e}}}}(),i}()}));
package/default.env ADDED
File without changes
@@ -0,0 +1,27 @@
1
+ import axios from 'axios';
2
+
3
+ import config from '../config';
4
+ import { handleError } from '../errors';
5
+
6
+ const {
7
+ APIS: {
8
+ BACKEND_TEMPLATE: {
9
+ BASE_URL,
10
+ ENDPOINTS: { DUMMY },
11
+ },
12
+ },
13
+ } = config;
14
+
15
+ /*
16
+ * Returns a random number after calling the Backend Template
17
+ * @return {Object} data - JSON object returned by the API
18
+ */
19
+ export const ping = async () => {
20
+ let data = null;
21
+ try {
22
+ ({ data } = await axios.get(`${BASE_URL}${DUMMY}`));
23
+ } catch (error) {
24
+ handleError(error);
25
+ }
26
+ return data;
27
+ };
package/lib/config.js ADDED
@@ -0,0 +1,12 @@
1
+ const config = {
2
+ APIS: {
3
+ BACKEND_TEMPLATE: {
4
+ BASE_URL: '/api/backend-template',
5
+ ENDPOINTS: {
6
+ DUMMY: '/dummy',
7
+ },
8
+ },
9
+ },
10
+ };
11
+
12
+ export default config;
package/lib/context.js ADDED
@@ -0,0 +1,10 @@
1
+ import { setContext as setErrorContext } from '@apolitical/error-reporting';
2
+
3
+ export const setContext = ({ origin, gcpErrorsApiKey, serviceName }) => {
4
+ // Setup error reporting context
5
+ setErrorContext({
6
+ origin,
7
+ accessToken: gcpErrorsApiKey,
8
+ serviceName,
9
+ });
10
+ };
package/lib/errors.js ADDED
@@ -0,0 +1,23 @@
1
+ import { reportError } from '@apolitical/error-reporting';
2
+
3
+ export const handleError = async (error) => {
4
+ let errorMessage = 'Error at Apolitical SDK: ';
5
+ if (error.response) {
6
+ // The request was made and the server responded with a status code that falls out of the range of 2xx
7
+ errorMessage += JSON.stringify(error.response);
8
+ } else if (error.request) {
9
+ // The request was made but no response was received
10
+ errorMessage += JSON.stringify(error.request);
11
+ } else {
12
+ // Something happened in setting up the request that triggered an error
13
+ errorMessage += error.message;
14
+ }
15
+ // Log the error (on the client browser)
16
+ console.warn(errorMessage);
17
+ // Report the error (to GCP) but prevent exceptions
18
+ try {
19
+ await reportError(new Error(errorMessage));
20
+ } catch (error2) {
21
+ console.warn(`Cannot report error: ${error2.message}`);
22
+ }
23
+ };
package/lib/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import { ping } from './apis/template';
2
+ import { setContext } from './context';
3
+
4
+ const sdk = {
5
+ setContext,
6
+ template: {
7
+ ping,
8
+ },
9
+ };
10
+
11
+ export default sdk;
package/package.json ADDED
@@ -0,0 +1,101 @@
1
+ {
2
+ "name": "@apolitical/sdk",
3
+ "version": "0.0.1-beta.3",
4
+ "description": "Browser library to interact with Apolitical's APIs",
5
+ "author": "Apolitical Group Limited <engineering@apolitical.co>",
6
+ "license": "MIT",
7
+ "main": "build/index.js",
8
+ "scripts": {
9
+ "test": "jest --runInBand",
10
+ "unit-test": "jest test/unit/* --bail --runInBand --passWithNoTests",
11
+ "integration-test": "jest test/integration/* --bail --runInBand --passWithNoTests",
12
+ "build": "webpack --config webpack.config.js",
13
+ "lint": "eslint --ext .js ./lib",
14
+ "format": "prettier --write 'lib/**/*.+(js|json)'",
15
+ "lint-format": "lint-staged",
16
+ "prepare": "husky install"
17
+ },
18
+ "keywords": [
19
+ "JavaScript",
20
+ "Browser",
21
+ "SDK"
22
+ ],
23
+ "dependencies": {
24
+ "@apolitical/error-reporting": "0.0.1",
25
+ "axios": "0.24.0"
26
+ },
27
+ "peerDependencies": {
28
+ "@apolitical/error-reporting": "0.0.1",
29
+ "axios": "0.24.0"
30
+ },
31
+ "devDependencies": {
32
+ "@apolitical/eslint-config": "0.0.1",
33
+ "@babel/core": "7.16.7",
34
+ "babel-eslint": "10.1.0",
35
+ "babel-loader": "8.2.3",
36
+ "babel-preset-react-app": "10.0.1",
37
+ "husky": "7.0.4",
38
+ "jest": "27.4.7",
39
+ "jest-junit": "13.0.0",
40
+ "lint-staged": "12.1.5",
41
+ "webpack": "5.65.0",
42
+ "webpack-cli": "4.9.1"
43
+ },
44
+ "eslintConfig": {
45
+ "extends": [
46
+ "eslint:recommended",
47
+ "plugin:prettier/recommended",
48
+ "plugin:jest/recommended"
49
+ ],
50
+ "env": {
51
+ "browser": true,
52
+ "node": true,
53
+ "es6": true,
54
+ "jest": true
55
+ },
56
+ "plugins": [
57
+ "jest"
58
+ ],
59
+ "parser": "babel-eslint"
60
+ },
61
+ "prettier": "@apolitical/eslint-config/prettier.config",
62
+ "browserslist": {
63
+ "production": [
64
+ ">0.2%",
65
+ "not dead",
66
+ "not op_mini all",
67
+ "ie 11"
68
+ ]
69
+ },
70
+ "jest": {
71
+ "bail": true,
72
+ "clearMocks": true,
73
+ "collectCoverage": true,
74
+ "collectCoverageFrom": [
75
+ "<rootDir>/lib/**/*.js"
76
+ ],
77
+ "coveragePathIgnorePatterns": [
78
+ "<rootDir>/node_modules/"
79
+ ],
80
+ "setupFiles": [
81
+ "./test/setupTests.js"
82
+ ],
83
+ "reporters": [
84
+ "default",
85
+ "jest-junit"
86
+ ],
87
+ "testResultsProcessor": "jest-junit"
88
+ },
89
+ "babel": {
90
+ "presets": [
91
+ "react-app"
92
+ ]
93
+ },
94
+ "engines": {
95
+ "node": ">=12.20.1"
96
+ },
97
+ "lint-staged": {
98
+ "*.js": "eslint --cache --fix --ignore-path .gitignore",
99
+ "*.+(js|json)": "prettier --write --ignore-path .gitignore"
100
+ }
101
+ }
@@ -0,0 +1,11 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`Apolitical SDK Context Set Context should set error reporting context 1`] = `
4
+ Array [
5
+ Object {
6
+ "accessToken": "some-gcp-errors-api-key",
7
+ "origin": "some-origin",
8
+ "serviceName": "some-service-name",
9
+ },
10
+ ]
11
+ `;
@@ -0,0 +1,27 @@
1
+ import { setContext as setErrorContext } from '@apolitical/error-reporting';
2
+
3
+ import sdk from '../lib';
4
+
5
+ describe('Apolitical SDK', () => {
6
+ describe('Context', () => {
7
+ const { setContext } = sdk;
8
+
9
+ describe('Set Context', () => {
10
+ const options = {
11
+ origin: 'some-origin',
12
+ gcpErrorsApiKey: 'some-gcp-errors-api-key',
13
+ serviceName: 'some-service-name',
14
+ };
15
+
16
+ beforeEach(() => {
17
+ setErrorContext.mockReturnValue();
18
+ });
19
+
20
+ test('should set error reporting context', () => {
21
+ setContext(options);
22
+ expect(setErrorContext).toHaveBeenCalledTimes(1);
23
+ expect(setErrorContext.mock.calls[0]).toMatchSnapshot();
24
+ });
25
+ });
26
+ });
27
+ });
@@ -0,0 +1,39 @@
1
+ import { reportError } from '@apolitical/error-reporting';
2
+
3
+ import { handleError } from '../lib/errors';
4
+
5
+ describe('Apolitical SDK', () => {
6
+ describe('Errors', () => {
7
+ describe('Handle Error', () => {
8
+ beforeEach(() => {
9
+ reportError.mockResolvedValue();
10
+ });
11
+
12
+ test('should log response error', async () => {
13
+ await handleError({ response: { data: 'some response' } });
14
+ expect(console.warn.mock.calls[0][0]).toEqual('Error at Apolitical SDK: {"data":"some response"}');
15
+ });
16
+
17
+ test('should log request error', async () => {
18
+ await handleError({ request: { data: 'some request' } });
19
+ expect(console.warn.mock.calls[0][0]).toEqual('Error at Apolitical SDK: {"data":"some request"}');
20
+ });
21
+
22
+ test('should log message error', async () => {
23
+ await handleError({ message: 'some message' });
24
+ expect(console.warn.mock.calls[0][0]).toEqual('Error at Apolitical SDK: some message');
25
+ });
26
+
27
+ test('should report error', async () => {
28
+ await handleError({ message: 'some message' });
29
+ expect(reportError).toHaveBeenCalledTimes(1);
30
+ });
31
+
32
+ test('should catch errors when reporting', async () => {
33
+ reportError.mockRejectedValueOnce(new Error('something went wrong'));
34
+ await handleError({ message: 'some message' });
35
+ expect(console.warn.mock.calls[1][0]).toEqual('Cannot report error: something went wrong');
36
+ });
37
+ });
38
+ });
39
+ });
@@ -0,0 +1,13 @@
1
+ // Mock dependencies
2
+ jest.mock('axios');
3
+ jest.mock('@apolitical/error-reporting', () => {
4
+ return {
5
+ reportError: jest.fn(),
6
+ setContext: jest.fn(),
7
+ };
8
+ });
9
+
10
+ // Overrides console error & warn when testing
11
+ // NB: Comment out this line to check errors when testing
12
+ console.error = jest.fn();
13
+ console.warn = jest.fn();
@@ -0,0 +1,33 @@
1
+ import axios from 'axios';
2
+ import { reportError } from '@apolitical/error-reporting';
3
+
4
+ import sdk from '../lib';
5
+
6
+ describe('Apolitical SDK', () => {
7
+ describe('Backend Template', () => {
8
+ const {
9
+ template: { ping },
10
+ } = sdk;
11
+
12
+ describe('Ping (Dummy Endpoint)', () => {
13
+ const payload = { data: { result: 123 } };
14
+
15
+ beforeEach(() => {
16
+ reportError.mockResolvedValue();
17
+ axios.get.mockResolvedValue(payload);
18
+ });
19
+
20
+ test('should return a number', async () => {
21
+ const { result } = await ping();
22
+ expect(result).toEqual(expect.any(Number));
23
+ });
24
+
25
+ test('should catch unexpected errors', async () => {
26
+ axios.get.mockRejectedValueOnce(new Error('something went wrong'));
27
+ const result = await ping();
28
+ expect(result).toStrictEqual(null);
29
+ expect(reportError).toHaveBeenCalledTimes(1);
30
+ });
31
+ });
32
+ });
33
+ });
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+ module.exports = {
6
+ mode: 'production',
7
+ entry: {
8
+ index: path.resolve(__dirname, 'lib', 'index.js'),
9
+ },
10
+ output: {
11
+ path: path.resolve(__dirname, 'build'),
12
+ filename: 'index.js',
13
+ library: {
14
+ name: 'ApoliticalSDK',
15
+ type: 'umd',
16
+ },
17
+ globalObject: 'this',
18
+ },
19
+ externals: {
20
+ axios: 'axios',
21
+ '@apolitical/error-reporting': '@apolitical/error-reporting',
22
+ },
23
+ optimization: {
24
+ splitChunks: {
25
+ chunks: 'all',
26
+ },
27
+ minimize: true,
28
+ },
29
+ };