How to use accepts - 10 common examples

To help you get started, we’ve selected a few accepts 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 freeCodeCamp / freeCodeCamp / api-server / server / middlewares / error-handlers.js View on Github external
return function(err, req, res, next) {
    const handled = unwrapHandledError(err);
    // respect handled error status
    let status = handled.status || err.status || res.statusCode;
    if (!handled.status && status < 400) {
      status = 500;
    }
    res.status(status);

    // parse res type
    const accept = accepts(req);
    const type = accept.type('html', 'json', 'text');

    const redirectTo = handled.redirectTo || `${homeLocation}/`;
    const message =
      handled.message ||
      'Oops! Something went wrong. Please try again in a moment.';

    if (isDev) {
      console.error(err);
    }

    if (type === 'html') {
      if (typeof req.flash === 'function') {
        req.flash(handled.type || 'danger', message);
      }
      return res.redirectWithFlash(redirectTo);
github comfuture / nuxt-payload / modules / payload / server.js View on Github external
.then(data => {
      if (accepts(req).type(["html", "json"]) === "json") {
        res.setHeader("Surrogate-Control", "no-store");
        res.setHeader(
          "Cache-Control",
          "no-store, no-cache, must-revalidate, proxy-revalidate"
        );
        res.setHeader("Pragma", "no-cache");
        res.setHeader("Expires", "0");
        res.json(data);
      } else {
        // XXX: url of sub mounted router points to parents router, so nuxt will try to render 1st depth router's url
        req.url = req.originalUrl;
        nuxt();
      }
    })
    .catch(error => {
github dpeek / dgraphql-serverless / src / responder.js View on Github external
function canDisplayGraphiQL (
  event: LambdaAPIGatewayProxyEvent,
  params: GraphQLParams
): boolean {
  // If `raw` exists, GraphiQL mode is not enabled.
  // Allowed to show GraphiQL if not requested as raw and this request
  // prefers HTML over JSON.
  const request = { headers: mapHeaders(event.headers) }
  return !params.raw && accepts(request).types(['json', 'html']) === 'html'
}
github terascope / teraslice / packages / data-access-plugin / src / query-point / dynamic-server.ts View on Github external
loginErrorHandler(req, res, async () => {
                const user = (await utils.login(get(req, 'aclManager'), req)) as User;
                if (user.role == null) {
                    throw new TSError(`User ${user.username} missing role `, {
                        statusCode: 403,
                        context: {
                            user,
                        },
                    });
                }

                if (this.playgroundOptions && req.method === 'GET') {
                    const accept = accepts(req);
                    const types = accept.types() as string[];
                    const prefersHTML = types.find((x: string) => x === 'text/html' || x === 'application/json') === 'text/html';
                    if (prefersHTML) {
                        const { href: endpoint } = new URL(`${req.baseUrl}${req.url.slice(1)}`, `${req.protocol}://${req.headers.host}${req.baseUrl}`);

                        const playgroundRenderPageOptions: PlaygroundRenderPageOptions = {
                            ...this.playgroundOptions,
                            endpoint,
                            subscriptionEndpoint: endpoint,
                            settings: {
                                'editor.reuseHeaders': true,
                                // @ts-ignore
                                'schema.polling.interval': 10000,
                                workspaceName: endpoint,
                                config: {
                                    app: {
github meetup / meetup-web-platform / src / routes.js View on Github external
handler: (request, reply) => {
			const requestLanguage = Accepts(request).language(Object.keys(renderRequestMap));
			request.log(['info'], chalk.green(`Request received for ${request.url.href} (${requestLanguage})`));

			return renderRequestMap[requestLanguage](request)
				.do(() => request.log(['info'], chalk.green('HTML response ready')))
				.subscribe(({ result, statusCode }) => {
					// response is sent when this function returns (`nextTick`)
					const response = reply(result)
						.code(statusCode);

					reply.track(response, 'session');
				});
		},
	};
github meetup / meetup-web-platform / packages / mwp-language-plugin / src / util / getLanguage.js View on Github external
export const getBrowserLang: ParseRequestLang = (request: HapiRequest) => {
	const { supportedLangs } = getServerSettings(request);
	return Accepts(request).language(supportedLangs);
};
github zeit / next.js / examples / with-higher-order-component / hocs / withLanguages.js View on Github external
WithLanguages.getInitialProps = async context => {
    const languages = context.req
      ? accepts(context.req).languages()
      : navigator.languages

    return {
      ...(Page.getInitialProps ? await Page.getInitialProps(context) : {}),
      languages,
    }
  }
github meetup / meetup-web-platform / src / util / languageUtils.js View on Github external
export const getBrowserLang = (request, supportedLangs) =>
	Accepts(request).language(supportedLangs);
github dazejs / daze / packages / framework / src / request / index.ts View on Github external
get accepts() {
    if (!this._accepts) this._accepts = accepts(this.req);
    return this._accepts;
  }
github huluoyang / freecodecamp.cn / server / boot / challenge.js View on Github external
function completedChallenge(req, res, next) {
    req.checkBody('id', 'id must be a ObjectId').isMongoId();
    req.checkBody('name', 'name must be at least 3 characters')
      .isString()
      .isLength({ min: 3 });
    req.checkBody('challengeType', 'challengeType must be an integer')
      .isNumber();

    const type = accepts(req).type('html', 'json', 'text');

    const errors = req.validationErrors(true);

    if (errors) {
      if (type === 'json') {
        return res.status(403).send({ errors });
      }

      log('errors', errors);
      return res.sendStatus(403);
    }

    const completedDate = Date.now();
    const {
      id,
      name,

accepts

Higher-level content negotiation

MIT
Latest version published 2 years ago

Package Health Score

76 / 100
Full package analysis

Popular accepts functions