How to use http-status - 10 common examples

To help you get started, we’ve selected a few http-status examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zalando-incubator / authmosphere / integration-test / oauth-tooling / middlewares.spec.ts View on Github external
addAuthenticationEndpointWithoutRequiredScopes();

    // when
    const promise = fetch('http://127.0.0.1:30002/resource/user', {
      method: 'GET',
      headers: {
        authorization: authHeader
      }
    })
    .then((res) => {

      return res.status;
    });

    // then
    return expect(promise).to.become(HttpStatus.FORBIDDEN);
  });
github SoftwareEngineeringDaily / software-engineering-daily-api / server / controllers / auth.controller.js View on Github external
const cbError = err => {
    if (err) {
      console.log(err); // eslint-disable-line
      const error = new APIError(
        'There was a problem getting a signed url',
        httpStatus.SERVICE_UNAVAILABLE,
        true
      );
      return next(error);
    }
  };
  signS3(config.aws.profilePicBucketName, fileType, newFileName, cbSuccess, cbError);
github SoftwareEngineeringDaily / software-engineering-daily-api / server / controllers / company.controller.js View on Github external
const cbError = err => {
      if (err) {
        console.log(err); // eslint-disable-line
        const error = new APIError(
          'There was a problem getting a signed url',
          httpStatus.SERVICE_UNAVAILABLE,
          true
        );
        return next(error);
      }
    };
    signS3(config.aws.profilePicBucketName, fileType, newFileName, cbSuccess, cbError);
github box / box-node-sdk / lib / token-manager.js View on Github external
.then(response => {

				// Response Error: The API is telling us that we attempted an invalid token grant. This
				// means that our refresh token or auth code has exipred, so propagate an "Expired Tokens"
				// error.
				if (response.body && response.body.error && response.body.error === 'invalid_grant') {
					var errDescription = response.body.error_description;
					var message = errDescription ? `Auth Error: ${errDescription}` : undefined;
					throw errors.buildAuthError(response, message);
				}

				// Unexpected Response: If the token request couldn't get a valid response, then we're
				// out of options. Build an "Unexpected Response" error and propagate it out for the
				// consumer to handle.
				if (response.statusCode !== httpStatusCodes.OK || response.body instanceof Buffer) {
					throw errors.buildUnexpectedResponseError(response);
				}

				// Check to see if token response is valid in case the API returns us a 200 with a malformed token
				if (!isValidTokenResponse(formParams.grant_type, response.body)) {
					throw errors.buildResponseError(response, 'Token format from response invalid');
				}

				// Got valid token response. Parse out the TokenInfo and propagate it back.
				return getTokensFromGrantResponse(response.body);
			});
	},
github shortlist-digital / tapestry-wp / src / server / handle-dynamic.js View on Github external
async (err, asyncProps) => {
              // 500 if error from AsyncProps
              if (err) {
                log.error({ err })
                return reply(err, HTTPStatus.INTERNAL_SERVER_ERROR)
              }

              const response = handleApiResponse(
                idx(asyncProps, _ => _.propsArray[0].data),
                renderProps.routes[1]
              )

              const status = idx(response, _ => _.code)
                ? response.code
                : HTTPStatus.OK

              const cacheKey = normaliseUrlPath(request.url.pathname)

              // Find HTML based on path - might be undefined
              const cachedHTML = await cache.get(cacheKey)
              log.debug(
                `Cache contains ${chalk.green(cacheKey)} in html: ${Boolean(
                  cachedHTML
                )}`
              )

              // respond with HTML from cache if not undefined
              if (cachedHTML && isPreview) {
                log.silly(
                  `HTML is in cache but skipped for preview ${chalk.green(
                    cacheKey
github zenprotocol / explorer / server / components / api / transactions / transactionsController.js View on Github external
asset,
          amount
        };
      });

      for (let i = 0; i < tx.inputs.length; i++) {
        const input = tx.inputs[i];
        const outpoint = {
          txHash: input.input.txHash.hash,
          index: input.input.index,
        };
        // search for this tx and index
        const output = await outputsDAL.findOutpoint(outpoint.txHash, outpoint.index);

        if (!output) {
          throw new HttpError(httpStatus.BAD_REQUEST, 'One of the inputs is not yet in the blockchain');
        }

        txCustom.Inputs.push({
          id: i + 1, // fake id
          Output: output,
        });
      }

      const assets = getTransactionAssets(txCustom);
      res.status(httpStatus.OK).json(jsonResponse.create(httpStatus.OK, assets));
    } catch (error) {
      throw new HttpError(error.status || httpStatus.INTERNAL_SERVER_ERROR, error.customMessage);
    }
  },
  create: async function(req, res) {
github shortlist-digital / tapestry-wp / src / shared / route-wrapper.js View on Github external
const RouteWrapper = config => {
  // if user routes have been defined, take those in preference to the defaults
  const errorResponse = {
    code: HTTPStatus.NOT_FOUND,
    message: HTTPStatus[HTTPStatus.NOT_FOUND]
  }
  const routes = config.routes || defaultRoutes(config.components)
  const ErrorComponent = () =>
    RenderError({
      config,
      response: errorResponse
    })
  // loops over routes and return react-router  components
  return (
    
      {routes.map(route => {
        // cancel if component not defined in user config, joi will validate user routes for component/path keys
        if (!route.component && !route.getComponent) {
          route.component = null
        }
        // on 'route' event:
github bookbrainz / bookbrainz-site / src / server / routes / auth.js View on Github external
if (!deleteAuthorizationGranted) {
		// Return an error status code - not able to get authorization
		return status.BAD_REQUEST;
	}

	// Try to delete the user
	const deleteUserByMetaBrainzID =
		orm.func.user.deleteUserByMetaBrainzID(orm.knex);

	let success = false;
	try {
		success = await deleteUserByMetaBrainzID(metabrainzUserID);
	}
	catch (err) {
		// Any kind of uncaught error here, give an ISE
		return status.INTERNAL_SERVER_ERROR;
	}

	if (success) {
		// If the user could be deleted, return a 200 response.
		return status.OK;
	}

	// Otherwise, the user was not found, return a 404 response.
	return status.NOT_FOUND;
}
github IBM / taxinomitis / src / lib / training / numbers.ts View on Github external
//  and then try the call again
            const project = await store.getProject(projectid);
            if (!project) {
                throw new Error('Project not found');
            }

            const classifier = await trainClassifier(project);
            if (classifier.status === 'Available') {
                body = await request.post(url, req);
            }
            else {
                log.error({ classifier, projectid }, 'Failed to create missing classifier for test');
                throw new Error('Failed to create classifier');
            }
        }
        else if (err.statusCode === httpStatus.INTERNAL_SERVER_ERROR &&
                 err.message.includes("Input contains NaN, infinity or a value too large for dtype('float32')"))
        {
            log.error({ err, data }, 'Value provided outside of valid range?');
            throw err;
        }
        else {
            throw err;
        }
    }
    return Object.keys(body)
            .map((key) => {
                return {
                    class_name : key,
                    confidence : body[key],
                    classifierTimestamp,
                };
github box / box-node-sdk / lib / box-client.js View on Github external
function isUnauthorizedDueToExpiredAccessToken(response) {
	// There are three cases to consider:
	// 1) The response body is a Buffer. This indicates that the request was malformed (i.e. malformed url) so return false.
	// 2) The status code is UNAUTHORIZED and the response body is an empty object or null. This indicates that the access tokens are expired, so return true.
	// 3) The status code is UNAUTHORIZED and the response body is a non-empty object. This indicates that the 401 was returned for some reason other
	//    than expired tokens, so return false.

	if (Buffer.isBuffer(response.body)) {
		return false;
	}

	var isResponseStatusCodeUnauthorized = response.statusCode === httpStatusCodes.UNAUTHORIZED,
		isResponseBodyEmpty = !response.body || Object.getOwnPropertyNames(response.body).length === 0;
	return isResponseStatusCodeUnauthorized && isResponseBodyEmpty;
}