auth_request.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { Response, Options } from "got";
  2. const got = require("got");
  3. const pkg = require("../../package.json");
  4. export class AuthRequest {
  5. static readonly urlRoot: NonNullable<Options["prefixUrl"]> =
  6. "https://app.lokalise.com/oauth2/";
  7. static async createPromise(
  8. uri: string,
  9. method: Options["method"],
  10. body: object | object[] | null,
  11. host?: string
  12. ): Promise<any> {
  13. const options: Options = {
  14. method: method,
  15. prefixUrl: host ?? this.urlRoot,
  16. headers: {
  17. Accept: "application/json",
  18. "User-Agent": `node-lokalise-api/${pkg.version}`,
  19. },
  20. agent: false,
  21. throwHttpErrors: false,
  22. decompress: false,
  23. };
  24. options["body"] = JSON.stringify(body);
  25. try {
  26. const response: Response = await got(uri, options);
  27. const responseJSON = JSON.parse(<string>response.body);
  28. if (response.statusCode > 399) {
  29. return Promise.reject({
  30. ...{ code: response.statusCode },
  31. ...responseJSON,
  32. });
  33. }
  34. return Promise.resolve({ json: responseJSON, headers: response.headers });
  35. } catch (err) {
  36. /* istanbul ignore next */
  37. return Promise.reject(err);
  38. }
  39. }
  40. }