Skip to content

Commit

Permalink
feat(package): esm only
Browse files Browse the repository at this point in the history
  • Loading branch information
MathRobin committed Oct 6, 2023
1 parent a119eda commit d299c81
Show file tree
Hide file tree
Showing 23 changed files with 958 additions and 1,107 deletions.
4 changes: 2 additions & 2 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ env:
plugins:
- jest
ignorePatterns:
- "**/*.test.js"
- "**/*.d.ts"
extends:
- eslint:recommended
- prettier
parserOptions:
ecmaVersion: 2021
ecmaVersion: 2022
sourceType: module
4 changes: 3 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install modules
run: yarn
- name: Run lint
run: yarn lint
- name: Run lint
run: yarn test
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Don't edit this part

.yarn/cache/*.zip
coverage_cjs

# Created by https://www.toptal.com/developers/gitignore/api/node,intellij+all,yarn
# Edit at https://www.toptal.com/developers/gitignore?templates=node,intellij+all,yarn
Expand Down
2 changes: 1 addition & 1 deletion .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

yarn lint
yarn test
git add index.esm.js index.cjs index.esm.d.ts
git add index.js index.d.ts
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
18.13.0
18.18.0
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,106 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![Static Badge](https://img.shields.io/badge/coverage-100-brightgreen)
![Static Badge](https://img.shields.io/badge/release-3.0.1-blue)
[![test](https://github.com/mathrobin/lambda-returns/actions/workflows/test.yml/badge.svg)](https://github.com/mathrobin/lambda-returns/actions/workflows/test.yml)

# lambda-returns

Provides shorthand to manage AWS lambda result. And provides test helper methods too!

ESM only since v3. Typings included.

## Usage

Deadly simple

```javascript
import { ok, internalServerError } from "lambda-returns";

export default async () => {
try {

return ok({
status: "success"
});
} catch (err) {

return internalServerError({
status: "error",
error: err
});
}
}
```

instead of that non-funny code:

```javascript
export default async () => {
try {

return {
statusCode: 200,
body: JSON.stringify({
status: "success"
}),
};
} catch (err) {

return {
statusCode: 500,
body: JSON.stringify({
status: "error",
error: err
}),
};
}
}
```

### Test helpers methods

Not enough for you? For me too. This package provides a simple way to test your return result from your AWS lambda
handler method.

```javascript
import { isOk, isBadRequest } from "lambda-returns";

expect(isOk(result)).toBeTruthy();
expect(isBadRequest(result)).toBeTruthy();
```

## Pros

- No prod dependency
- Typings provided
- lower than 45kB unpacked

### Stop remember codes

You don't have to remember status code values. Just the name which is more "menaningful". Who really knows the code of:

- insufficientStorage
- partialContent
- imATeapot
. You ? Me no. And don't want/need to.

### Stop polluting your business logic

Moreover, into vanilla AWS lambda way, you need to return a string as body. But just stringify your result is dangerous,
if you have a dynamic result, maybe is null, maybe is undefined, maybe you already have a string.

F*ck! I don't want to care of it in my business logic! `lambda-returns` manages it for you.

## Cons

There is only one known pitfall. We can't technically export "continue" status due to it's a reserved word in
JavaScript.

```javascript
export const continue
= {}; // or whatever;
```

This is just forbidden. If you knwon any way to go over this problem, tell me.

Despite to this problem, test helper method `isContinue` is available.
84 changes: 4 additions & 80 deletions build.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,9 @@
import fs from 'fs';

const codes = {
continue: 100,
switchingProtocols: 101,
processing: 102,
ok: 200,
created: 201,
accepted: 202,
nonAuthoritativeInformation: 203,
noContent: 204,
resetContent: 205,
partialContent: 206,
multiStatus: 207,
multipleChoices: 300,
movedPermanently: 301,
movedTemporarily: 302,
seeOther: 303,
notModified: 304,
useProxy: 305,
temporaryRedirect: 307,
badRequest: 400,
unauthorized: 401,
paymentRequired: 402,
forbidden: 403,
notFound: 404,
methodNotAllowed: 405,
notAcceptable: 406,
proxyAuthenticationRequired: 407,
requestTimeOut: 408,
conflict: 409,
gone: 410,
lengthRequired: 411,
preconditionFailed: 412,
requestEntityTooLarge: 413,
requestUriTooLarge: 414,
unsupportedMediaType: 415,
requestedRangeNotSatisfiable: 416,
expectationFailed: 417,
imATeapot: 418,
unprocessableEntity: 422,
locked: 423,
failedDependency: 424,
unorderedCollection: 425,
upgradeRequired: 426,
preconditionRequired: 428,
tooManyRequests: 429,
requestHeaderFieldsTooLarge: 431,
internalServerError: 500,
notImplemented: 501,
badGateway: 502,
serviceUnavailable: 503,
gatewayTimeOut: 504,
httpVersionNotSupported: 505,
variantAlsoNegotiates: 506,
insufficientStorage: 507,
bandwidthLimitExceeded: 509,
notExtended: 510,
networkAuthenticationRequired: 511,
};
import capitalizeFirstLetter from './src/capitalize_first/index.js';
import codes from './codes.js';

const exportsEsm = [];
const exportsCjs = [];

function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}

Object.entries(codes)
.filter(([message]) => {
Expand All @@ -77,12 +16,6 @@ Object.entries(codes)
headers,
body: result ? typeof result === 'string' ? result : JSON.stringify(result) : null,
});`);

exportsCjs.push(`module.exports.${message} = (result, headers = {}) => ({
statusCode: ${code},
headers,
body: result ? typeof result === 'string' ? result : JSON.stringify(result) : null,
});`);
});

Object.entries(codes).forEach(([message, code]) => {
Expand All @@ -91,17 +24,8 @@ Object.entries(codes).forEach(([message, code]) => {
)} = (response) => {
return response.statusCode === ${code};
};`);

exportsCjs.push(`module.exports.is${capitalizeFirstLetter(
message
)} = (response) => {
return response.statusCode === ${code};
};`);
});

fs.writeFile('./index.esm.js', exportsEsm.join('\n\n'), () => {
console.log('Version ES Module generated');
});
fs.writeFile('./index.cjs', exportsCjs.join('\n\n'), () => {
console.log('Version CommonJs generated');
fs.writeFile('./index.js', exportsEsm.join('\n\n'), () => {
console.log('Module generated');
});
58 changes: 58 additions & 0 deletions codes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
export default {
continue: 100,
switchingProtocols: 101,
processing: 102,
ok: 200,
created: 201,
accepted: 202,
nonAuthoritativeInformation: 203,
noContent: 204,
resetContent: 205,
partialContent: 206,
multiStatus: 207,
multipleChoices: 300,
movedPermanently: 301,
movedTemporarily: 302,
seeOther: 303,
notModified: 304,
useProxy: 305,
temporaryRedirect: 307,
badRequest: 400,
unauthorized: 401,
paymentRequired: 402,
forbidden: 403,
notFound: 404,
methodNotAllowed: 405,
notAcceptable: 406,
proxyAuthenticationRequired: 407,
requestTimeOut: 408,
conflict: 409,
gone: 410,
lengthRequired: 411,
preconditionFailed: 412,
requestEntityTooLarge: 413,
requestUriTooLarge: 414,
unsupportedMediaType: 415,
requestedRangeNotSatisfiable: 416,
expectationFailed: 417,
imATeapot: 418,
unprocessableEntity: 422,
locked: 423,
failedDependency: 424,
unorderedCollection: 425,
upgradeRequired: 426,
preconditionRequired: 428,
tooManyRequests: 429,
requestHeaderFieldsTooLarge: 431,
internalServerError: 500,
notImplemented: 501,
badGateway: 502,
serviceUnavailable: 503,
gatewayTimeOut: 504,
httpVersionNotSupported: 505,
variantAlsoNegotiates: 506,
insufficientStorage: 507,
bandwidthLimitExceeded: 509,
notExtended: 510,
networkAuthenticationRequired: 511,
};
Loading

0 comments on commit d299c81

Please sign in to comment.