Skip to content

Commit

Permalink
feature: Add typescript integration.
Browse files Browse the repository at this point in the history
  • Loading branch information
sundargs2000 committed Mar 22, 2021
1 parent 45b8cb2 commit 724a928
Show file tree
Hide file tree
Showing 36 changed files with 2,088 additions and 452 deletions.
27 changes: 27 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"@babel/core": "^7.12.10",
"@babel/plugin-transform-runtime": "^7.12.10",
"@babel/preset-env": "^7.12.10",
"@types/isomorphic-fetch": "0.0.35",
"@types/isomorphic-form-data": "^2.0.0",
"@types/node": "^14.14.35",
"chai": "^4.2.0",
"eslint": "^7.15.0",
"eslint-config-airbnb": "^18.2.1",
Expand All @@ -26,10 +29,11 @@
"eslint-plugin-react": "^7.21.5",
"mocha": "^8.2.1",
"prettier": "^2.2.1",
"sinon": "^9.2.1"
"sinon": "^9.2.1",
"typescript": "^4.2.3"
},
"scripts": {
"build": "babel --delete-dir-on-start -d lib/ src/",
"build": "tsc && babel --delete-dir-on-start -d lib/ src/",
"prepare": "npm run build",
"lint": "eslint . && prettier --loglevel=warn --check .",
"lint:fix": "eslint --fix . && prettier --loglevel=warn --write .",
Expand Down
105 changes: 60 additions & 45 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,63 @@
const helper = require('./helper');

async function api(baseUrl, config, method, params) {
const url = new URL(baseUrl);
const auth = Buffer.from(`${config.username}:${config.apiKey}`).toString(
'base64'
);
const authHeader = `Basic ${auth}`;
const options = { method, headers: { Authorization: authHeader } };
if (method === 'POST') {
options.body = new helper.FormData();
Object.keys(params).forEach((key) => {
let data = params[key];
if (Array.isArray(data)) {
data = JSON.stringify(data);
}
options.body.append(key, data);
"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());
});
} else if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.api = void 0;
const types_1 = require("./types");
const fetch = require('isomorphic-fetch');
const FormData = require('isomorphic-form-data');
function api(baseUrl, config, method, params) {
return __awaiter(this, void 0, void 0, function* () {
const url = new URL(baseUrl);
const auth = Buffer.from(`${config.username}:${config.apiKey}`).toString('base64');
const authHeader = `Basic ${auth}`;
const options = {
method,
headers: { Authorization: authHeader },
};
if (method === 'POST') {
options.body = new FormData();
Object.keys(params).forEach((key) => {
let data = params[key];
if (Array.isArray(data)) {
data = JSON.stringify(data);
}
options.body.append(key, data);
});
}
else if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
}
const response = yield fetch(url.href, options);
try {
return response.json();
}
catch (e) {
if (e instanceof SyntaxError) {
// We probably got a non-JSON response from the server.
// We should inform the user of the same.
let message = 'Server Returned a non-JSON response.';
if (response.status === 404) {
message += ` Maybe endpoint: ${method} ${response.url.replace(config.apiURL, '')} doesn't exist.`;
}
else {
message += ' Please check the API documentation.';
}
const error = new types_1.ZulipErrorResponse(message);
error.res = response;
throw error;
}
throw e;
}
});
}
const response = await helper.fetch(url.href, options);
try {
return response.json();
} catch (e) {
if (e instanceof SyntaxError) {
// We probably got a non-JSON response from the server.
// We should inform the user of the same.
let message = 'Server Returned a non-JSON response.';
if (response.status === 404) {
message += ` Maybe endpoint: ${method} ${response.url.replace(
config.apiURL,
''
)} doesn't exist.`;
} else {
message += ' Please check the API documentation.';
}
const error = new Error(message);
error.res = response;
throw error;
}
throw e;
}
}

module.exports = api;
exports.api = api;
63 changes: 63 additions & 0 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Config } from './zuliprc';
import { ZulipErrorResponse } from './types';
const fetch = require('isomorphic-fetch');
const FormData = require('isomorphic-form-data');

export type HttpMethod =
| "GET"
| "HEAD"
| "POST"
| "PUT"
| "DELETE"
| "TRACE"
| "OPTIONS"
| "CONNECT"
| "PATCH";

export async function api(baseUrl: string, config: Config, method: HttpMethod, params: any): Promise<any> {
const url: URL = new URL(baseUrl);
const auth: string = Buffer.from(`${config.username}:${config.apiKey}`).toString(
'base64'
);
const authHeader: string = `Basic ${auth}`;
const options: any = {
method,
headers: { Authorization: authHeader },
};
if (method === 'POST') {
options.body = new FormData();
Object.keys(params).forEach((key) => {
let data: string = params[key];
if (Array.isArray(data)) {
data = JSON.stringify(data);
}
options.body.append(key, data);
});
} else if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value as string);
});
}
const response: Response = await fetch(url.href, options);
try {
return response.json();
} catch (e) {
if (e instanceof SyntaxError) {
// We probably got a non-JSON response from the server.
// We should inform the user of the same.
let message: string = 'Server Returned a non-JSON response.';
if (response.status === 404) {
message += ` Maybe endpoint: ${method} ${response.url.replace(
config.apiURL,
''
)} doesn't exist.`;
} else {
message += ' Please check the API documentation.';
}
const error: ZulipErrorResponse = new ZulipErrorResponse(message);
error.res = response;
throw error;
}
throw e;
}
}
Loading

0 comments on commit 724a928

Please sign in to comment.