How to use the middy/middlewares.jsonBodyParser function in middy

To help you get started, we’ve selected a few middy 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 DavidWells / netlify-functions-workshop / lessons-code-complete / core-concepts / 7-using-middleware / functions / using-middleware.js View on Github external
return ({
    before: (handler, next) => {
      // might read options from `config`
    },
    after: (handler, next) => {
      // might read options from `config`
    },
    onError: (handler, next) => {
      // might read options from `config`
    }
  })
}

// Export the handler
exports.handler = middy(businessLogic)
  .use(jsonBodyParser())
  .use(myMiddleware())
github netlify / cli / src / functions-templates / js / using-middleware / using-middleware.js View on Github external
result: { type: 'string' },
          message: { type: 'string' }
        }
      }
    },
    required: ['body']
  }
}

/* Export inputSchema & outputSchema for automatic documentation */
exports.schema = schema

exports.handler = middy(businessLogic)
  .use(httpHeaderNormalizer())
  // parses the request body when it's a JSON and converts it to an object
  .use(jsonBodyParser())
  // validates the input
  .use(validator({ inputSchema: schema.input }))
  // handles common http errors and returns proper responses
  .use(httpErrorHandler())
github mcnamee / serverless-jwt-auth / app / Handlers / Users.js View on Github external
return userByEmail(queryValues[':em']) // Check if the new email already exists
    .then((foundUser) => {
      if (foundUser && foundUser.email) {
        // New email exists, and doesn't belong to the current user
        if (foundUser.email === queryValues[':em'] && foundUser.id !== id) {
          throw new Error('That email belongs to another user');
        }
      }
    })
    .then(() => DB.update(params).promise()) // Update the data to the DB
    .then(user => cb(null, {message: 'Success - user updated', data: user }));
}

module.exports.update = middy(update)
  .use(jsonBodyParser())
  .use(validatorMiddleware({ inputSchema: requestSchema.update }))
  .use(apiResponseMiddleware());
github MoonMail / MoonMail / campaigns-microservice-new / src / api / update.ts View on Github external
import { NormalizedEvent } from '../../common/@types';
import { apiRequestRoutine, logRoutine } from '../../common/middlewares';

interface Event extends NormalizedEvent {
  body: Campaign
};

export async function action({ body: campaign, pathParameters: { id: campaignId }, headers: { Authorization: authToken } }: Event): Promise {
  const {sub: userId}: TokenData = decryptor(authToken);
  campaign.userId = userId;

  return await campaignRepository.update(campaign, userId, campaignId);
}

export default middy(action)
  .use(jsonBodyParser())
  .use(apiRequestRoutine())
  .use(logRoutine());
github fourTheorem / slic-starter / slic-tools / middy-util.js View on Github external
Object.keys(exports).forEach(key => {
    const handler = middy(exports[key])
      .use(
        loggerMiddleware({
          logger: log
        })
      )
      .use(httpEventNormalizer())
      .use(jsonBodyParser())
      .use(cors())
      .use(autoProxyResponse())
      .use(httpErrorHandler())

    if (options.ssmParameters && process.env.SLIC_STAGE !== 'test') {
      handler.use(
        ssm({
          cache: true,
          names: options.ssmParameters,
          awsSdkOptions: {
            endpoint: process.env.SSM_ENDPOINT_URL
          }
        })
      )
    }
    result[key] = handler
github josephluck / internote / services / export / markdown.ts View on Github external
await S3.upload({
    Bucket: process.env.EXPORT_BUCKET,
    Key: S3UploadPath,
    Body: output,
    ACL: "public-read"
  }).promise();

  const src = `https://s3-${process.env.REGION}.amazonaws.com/${process.env.EXPORT_BUCKET}/${S3UploadPath}`;

  const response: ExportResponseDTO = { src };

  return callback(null, success(response));
};

export const handler = middy(markdown)
  .use(jsonBodyParser())
  .use(validator)
  .use(encodeResponse())
  .use(jsonErrorHandler())
  .use(cors());
github josephluck / internote / services / preferences / update.ts View on Github external
const update: UpdateHandler = async (event, _ctx, callback) => {
  const userId = getUserIdentityId(event);
  try {
    const preferences = await updatePreferencesById(userId, event.body);
    return callback(null, success(preferences));
  } catch (err) {
    if (err instanceof HttpError.NotFound) {
      throw notFound(`Preferences for user ${userId} not found`);
    } else {
      throw exception(err);
    }
  }
};

export const handler = middy(update)
  .use(jsonBodyParser())
  .use(validator)
  .use(encodeResponse())
  .use(jsonErrorHandler())
  .use(cors());
github MoonMail / MoonMail / campaigns-microservice-new / src / api / create.ts View on Github external
import { jsonBodyParser } from 'middy/middlewares';

interface Event extends NormalizedEvent {
  body: Campaign
};

export async function action({body: campaign, headers: {Authorization: authToken}}: Event): Promise {
  const {sub}: TokenData = decryptor(authToken);
  campaign.userId = sub;
  campaign.status = CampaignStatus.DRAFT;

  return await campaignRepository.save(campaign);
}

export default middy(action)
  .use(jsonBodyParser())
  .use(apiRequestRoutine())
  .use(logRoutine());
github MoonMail / MoonMail / campaigns-microservice-new / src / api / delete.ts View on Github external
import decryptor from '../lib/auth-token-decryptor';
import { apiRequestRoutine, logRoutine } from '../../common/middlewares';
import { TokenData } from '../types';

export async function action({pathParameters: {id: campaignId}, headers: {Authorization: authToken}}: APIGatewayEvent): Promise {
  const {sub: userId}: TokenData = decryptor(authToken);
  await campaignRepository.delete(userId, campaignId);

  return {
    statusCode: 204,
    body: ''
  };
}

export default middy(action)
  .use(jsonBodyParser())
  .use(apiRequestRoutine())
  .use(logRoutine());
github josephluck / internote / services / export / html.ts View on Github external
await S3.upload({
    Bucket: process.env.EXPORT_BUCKET,
    Key: S3UploadPath,
    Body: output,
    ACL: "public-read"
  }).promise();

  const src = `https://s3-${process.env.REGION}.amazonaws.com/${process.env.EXPORT_BUCKET}/${S3UploadPath}`;

  const response: ExportResponseDTO = { src };

  return callback(null, success(response));
};

export const handler = middy(html)
  .use(jsonBodyParser())
  .use(validator)
  .use(encodeResponse())
  .use(jsonErrorHandler())
  .use(cors());