How to use the http-errors function in http-errors

To help you get started, we’ve selected a few http-errors 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 graphql / express-graphql / src / parseBody.js View on Github external
}

  const rawBody = await readBody(req, typeInfo);
  // Use the correct body parser based on Content-Type header.
  switch (typeInfo.type) {
    case 'application/graphql':
      return { query: rawBody };
    case 'application/json':
      if (jsonObjRegex.test(rawBody)) {
        try {
          return JSON.parse(rawBody);
        } catch (error) {
          // Do nothing
        }
      }
      throw httpError(400, 'POST body sent invalid JSON.');
    case 'application/x-www-form-urlencoded':
      return querystring.parse(rawBody);
  }

  // If no Content-Type header matches, parse nothing.
  return {};
}
github stephank / castling.club / src / front / inbox.ts View on Github external
} catch (err) {
      throw createError(
        400,
        `Activity document could not be loaded: ${err.message}`
      );
    }

    const activity = getActivity(store, parsed.id);
    if (!activity.type || !activity.actor) {
      throw createError(400, "Incomplete activity object");
    }

    // Verify the actor signature.
    const publicKey = await signing.verify(ctx, raw, store);
    if (publicKey.owner !== activity.actor) {
      throw createError(400, "Signature does not match actor");
    }

    // Verify the activity is from the actor's origin.
    if (originOf(activity.actor) !== origin) {
      throw createError(400, "Activity and actor origins don't match");
    }

    // Load the actor document.
    try {
      await store.load(activity.actor);
    } catch (err) {
      throw createError(
        400,
        `Actor document could not be loaded: ${err.message}`
      );
    }
github stephank / castling.club / src / front / inbox.ts View on Github external
ctx.body = null;
      return;
    }

    // We currently handle just 'Create'.
    if (activity.type === AS("Create")) {
      // The object MUST be inlined in the raw JSON, according to spec.
      // This also means it was already loaded into the store.
      if (typeof parsed.object !== "object") {
        throw createError(400, "Invalid object in 'Create' activity");
      }

      const object = getObject(store, activity.object!);
      if (object.type === AS("Note")) {
        if (object.attributedTo !== activity.actor) {
          throw createError(
            400,
            "Activity creates note not attributed to the actor"
          );
        }

        // Amend object with convenience props.
        const objectExt = {
          ...object,
          actor: actor,
          contentText: extractText(object.content || ""),
          mentions: new Set()
        };
        for (const tagId of object.tags) {
          // Assume these are also inlined in the JSON, and thus loaded.
          // If they're not, they'll simply not pass the type check.
          const tag = getTag(store, tagId);
github albertogasparin / react-starterkit / www / all / index.js View on Github external
async function all({ request, redirect, render, app }, next) {
  const routes = require('../../app/routes').default; // enable hot reload server-side
  let location = request.url;
  let redirectLocation, renderProps;

  // Use react-router match() to check if valid route
  try {
    [redirectLocation, renderProps] = await new Promise((res, rej) => {
      match({ routes, location }, (e, ...v) => (e ? rej(e) : res(v)));
    });
  } catch (err) {
    throw createError(500, err);
  }

  if (redirectLocation) {
    return redirect(redirectLocation.pathname + redirectLocation.search, '/');
  }

  if (!renderProps) {
    throw createError(404);
  }

  /**
   * If you are NOT intersted in server-side rendering
   * then replace following code with just:
   *
   * render(indexTpl);
   */
github stephank / castling.club / src / front / inbox.ts View on Github external
}

    // Load the activity document.
    const store = jsonld.createStore();
    try {
      await store.load(parsed);
    } catch (err) {
      throw createError(
        400,
        `Activity document could not be loaded: ${err.message}`
      );
    }

    const activity = getActivity(store, parsed.id);
    if (!activity.type || !activity.actor) {
      throw createError(400, "Incomplete activity object");
    }

    // Verify the actor signature.
    const publicKey = await signing.verify(ctx, raw, store);
    if (publicKey.owner !== activity.actor) {
      throw createError(400, "Signature does not match actor");
    }

    // Verify the activity is from the actor's origin.
    if (originOf(activity.actor) !== origin) {
      throw createError(400, "Activity and actor origins don't match");
    }

    // Load the actor document.
    try {
      await store.load(activity.actor);
github chentsulin / koa-graphql / src / parseBody.js View on Github external
getBody(stream, { encoding: charset, length, limit }, function (err, body) {
    if (err) {
      return reject(
        err.type === 'encoding.unsupported' ?
          httpError(415, `Unsupported charset "${charset.toUpperCase()}".`) :
          httpError(400, `Invalid body: ${err.message}.`)
      );
    }

    try {
      // Decode and parse body.
      return resolve(parseFn(body));
    } catch (error) {
      return reject(error);
    }
  });
}
github alexanderlarin / ultimate-brainz / core / api.js View on Github external
.end((err, res) => {
                    if (!err && res.ok)
                        return resolve(res.body);
                    return reject(new HttpError(err.status, res ? (res.body && res.body.error) : err.message));
                });
        });
github softindex / uikernel / src / grid / models / GridExpressApi.js View on Github external
filesByRecordId[recordId] = {};
              }
              filesByRecordId[recordId][field] = buffer;
            }

            body = parseJson(body.rest, 'Incorrect "rest" json')
              .map(([recordId, record]) => {
                return [recordId, {
                  ...record,
                  ...filesByRecordId[recordId]
                }];
              });
          }

          if (!Array.isArray(body)) {
            throw httpError(422, 'Wrong data type to update');
          }

          try {
            const data = await model.update(body);
            result(null, data, req, res, next);
          } catch (err) {
            result(err, null, req, res, next);
          }
        })],
      create: [
github FSecureLABS / dref / dref / api / src / app.js View on Github external
app.use(function (req, res, next) {
  next(createError(404))
})
github arangodb / arangojs / src / connection.js View on Github external
return callback(e)
            }
          }
          if (
            res.body &&
            res.body.error &&
            res.body.hasOwnProperty('code') &&
            res.body.hasOwnProperty('errorMessage') &&
            res.body.hasOwnProperty('errorNum')
          ) {
            err = new ArangoError(res.body)
            err.response = res
            if (currentAttempt === 1 && err.errorNum === 21 && operation.retry(err)) return
            callback(err)
          } else if (res.statusCode >= 400) {
            err = httperr(res.statusCode)
            err.response = res
            if (currentAttempt === 1 && res.statusCode === 500 && operation.retry(err)) return
            callback(err)
          } else {
            if (expectBinary) res.body = rawBody
            callback(null, res)
          }
        }
      })
    })