How to use express-async-handler - 9 common examples

To help you get started, we’ve selected a few express-async-handler 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 archfirst / node-es6-rest-template / src / routes / api / books.js View on Github external
export const booksRouter = express.Router();

// Get all books
booksRouter.get(
    '/',
    asyncHandler(async (req, res) => {
        const books = await bookService.getBooks();
        res.send(books);
    })
);

// Get one book
booksRouter.get(
    '/:id',
    asyncHandler(async (req, res) => {
        const { id } = req.params;
        const book = await bookService.getBook(id);
        res.send(book);
    })
);
github microsoft / opensource-portal / routes / api / client / newOrgRepo.ts View on Github external
async function discoverUserIdentities(req: ReposAppRequest, res, next) {
  const apiContext = req.apiContext as IndividualContext;
  const providers = req.app.settings.providers as IProviders;
  const mailAddressProvider = providers.mailAddressProvider;
  // Try and also learn if we know their e-mail address to send the new repo mail to
  const upn = apiContext.corporateIdentity.username;
  try {
    const mailAddress = await GetAddressFromUpnAsync(mailAddressProvider, upn);
    if (mailAddress) {
      req['knownRequesterMailAddress'] = mailAddress;
    }
  } catch (ignoredError) { /* ignored */ }
  return next();
}

router.post('/repo/:repo', asyncHandler(discoverUserIdentities), asyncHandler(async function (req: ILocalApiRequest, res, next) {
  const config = req.app.settings.runtimeConfig;
  const organization = req.organization as Organization;
  if (organization.createRepositoriesOnGitHub) {
    return next(jsonError(`The GitHub organization ${organization.name} is configured as "createRepositoriesOnGitHub": repos should be created on GitHub.com directly and not through this wizard.`, 400));
  }
  const body = req.body;
  if (!body) {
    return next(jsonError('No body', 400));
  }
  req.apiVersion = req.query['api-version'] || req.headers['api-version'] || '2017-07-27';
  if (req.apiContext && req.apiContext.getGitHubIdentity()) {
    body['ms.onBehalfOf'] = req.apiContext.getGitHubIdentity().username;
  }
  // these fields do not need translation: name, description, private
  const approvalTypesToIds = config.github.approvalTypes.fields.approvalTypesToIds;
  if (!approvalTypesToIds[body.approvalType]) {
github staart / api / src / routes / index.ts View on Github external
asyncHandler(routeOrganizationSourcesPut)
  );
  app.get(
    "/organizations/:id/sources/:sourceId",
    authHandler,
    asyncHandler(routeOrganizationSourceGet)
  );
  app.patch(
    "/organizations/:id/sources/:sourceId",
    authHandler,
    asyncHandler(routeOrganizationSourceUpdate)
  );
  app.delete(
    "/organizations/:id/sources/:sourceId",
    authHandler,
    asyncHandler(routeOrganizationSourceDelete)
  );
  app.get(
    "/organizations/:id/data",
    authHandler,
    asyncHandler(routeOrganizationDataGet)
  );
  app.get(
    "/organizations/:id/events",
    authHandler,
    asyncHandler(routeOrganizationRecentEventsGet)
  );
};
github BigDataBoutique / ElastiQuill / backend / src / routes / social.js View on Github external
import _ from "lodash";
import express from "express";
import asyncHandler from "express-async-handler";

import * as blogPosts from "../services/blogPosts";
import * as social from "../services/social";
import { config } from "../app";
import { preparePost } from "./util";

const router = express.Router();

router.get(
  "/availability",
  asyncHandler(async (req, res) => {
    res.json(social.getAvailability(req.user.connected));
  })
);

router.post(
  "/post/linkedin/:id",
  asyncHandler(async (req, res) => {
    const post = await blogPosts.getItemById({ id: req.params.id });
    if (!req.user.connected.linkedin) {
      throw new Error("Linkedin is not connected");
    }

    const link = config.blog.url + preparePost(post).url;
    const imgUrl = post.metadata && post.metadata.header_image_url;
    try {
      const { token, profileId } = req.user.connected.linkedin;
github staart / api / src / routes / index.ts View on Github external
asyncHandler(routeOrganizationInvoicesGet)
  );
  app.get(
    "/organizations/:id/subscriptions",
    authHandler,
    asyncHandler(routeOrganizationSubscriptionsGet)
  );
  app.get(
    "/organizations/:id/pricing/:product",
    authHandler,
    asyncHandler(routeOrganizationPricingPlansGet)
  );
  app.get(
    "/organizations/:id/sources",
    authHandler,
    asyncHandler(routeOrganizationSourcesGet)
  );
  app.put(
    "/organizations/:id/sources",
    authHandler,
    asyncHandler(routeOrganizationSourcesPut)
  );
  app.get(
    "/organizations/:id/sources/:sourceId",
    authHandler,
    asyncHandler(routeOrganizationSourceGet)
  );
  app.patch(
    "/organizations/:id/sources/:sourceId",
    authHandler,
    asyncHandler(routeOrganizationSourceUpdate)
  );
github staart / api / src / routes / index.ts View on Github external
const routesOrganization = (app: Application) => {
  app.put("/organizations", authHandler, asyncHandler(routeOrganizationCreate));
  app.patch(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationUpdate)
  );
  app.get(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationGet)
  );
  app.delete(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationDelete)
  );
  app.get(
    "/organizations/:organizationId/memberships",
    authHandler,
    asyncHandler(routeMembershipList)
  );
github staart / api / src / routes / index.ts View on Github external
const routesOrganization = (app: Application) => {
  app.put("/organizations", authHandler, asyncHandler(routeOrganizationCreate));
  app.patch(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationUpdate)
  );
  app.get(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationGet)
  );
  app.delete(
    "/organizations/:id",
    authHandler,
    asyncHandler(routeOrganizationDelete)
  );
  app.get(
    "/organizations/:organizationId/memberships",
    authHandler,
    asyncHandler(routeMembershipList)
  );
  app.put(
    "/organizations/:organizationId/memberships",
    authHandler,
    asyncHandler(routeMembershipCreate)
  );
  app.get(
    "/organizations/:id/billing",
    authHandler,
    asyncHandler(routeOrganizationBillingGet)
  );
github BigDataBoutique / ElastiQuill / backend / src / routes / blog.js View on Github external
preparePage,
  preparePostJson,
  blogpostUrl,
  PageNotFoundError,
} from "./util";
import { config } from "../app";

const router = express.Router();

const PAGE_SIZE = 10;

events.onChange("post", () => clearPageCache(config.blog["blog-route-prefix"]));
router.get("/", cachePageHandler(asyncHandler(handlePostsRequest("index"))));

router.get("/page/:pageNum", asyncHandler(handlePostsRequest("index")));
router.get("/tagged/:tag", asyncHandler(handlePostsRequest("tagged")));
router.get(
  "/tagged/:tag/page/:pageNum",
  asyncHandler(handlePostsRequest("tagged"))
);
router.get("/series/:series", asyncHandler(handlePostsRequest("series")));
router.get(
  "/series/:series/page/:pageNum",
  asyncHandler(handlePostsRequest("series"))
);
router.get("/search", asyncHandler(handlePostsRequest("search")));
router.get("/search/page/:pageNum", asyncHandler(handlePostsRequest("search")));

router.get(
  "/rss",
  asyncHandler(async (req, res) => {
    const { items } = await cacheAndReturn("recent-items", async () => {
github microsoft / opensource-portal / routes / api / people / links.ts View on Github external
const username = req.params.username.toLowerCase();
  const operations = req.app.settings.operations as Operations;
  const skipOrganizations = req.query.showOrganizations !== undefined && !!req.query.showOrganizations;
  const showTimestamps = req.query.showTimestamps !== undefined && req.query.showTimestamps === 'true';
  const results = await getAllUsers(req.apiVersion, operations, skipOrganizations, showTimestamps);
  for (let i = 0; i < results.length; i++) {
    const entry = results[i];
    if (entry && entry.github && entry.github.login.toLowerCase() === username) {
      req.insights.trackMetric({ name: 'ApiRequestLinkByGitHubUsername', value: 1 });
      return res.json(entry);
    }
  }
  return next(jsonError('Could not find a link for the user', 404));
}));

router.get('/aad/userPrincipalName/:upn', asyncHandler(async (req: IApiRequest, res, next) => {
  const upn = req.params.upn;
  const operations = req.app.settings.operations;
  const skipOrganizations = req.query.showOrganizations !== undefined && !!req.query.showOrganizations;
  const showTimestamps = req.query.showTimestamps !== undefined && req.query.showTimestamps === 'true';
  const results = await getAllUsers(req.apiVersion, operations, skipOrganizations, showTimestamps);
  let r = [];
  for (let i = 0; i < results.length; i++) {
    const entry = results[i];
    if (entry && entry.aad && entry.aad.userPrincipalName === upn) {
      r.push(entry);
    }
  }
  req.insights.trackEvent({
    name: 'ApiRequestLinkByAadUpnResult',
    properties: {
      length: r.length.toString(),

express-async-handler

Express Error Handler for Async Functions

MIT
Latest version published 3 years ago

Package Health Score

56 / 100
Full package analysis

Popular express-async-handler functions