{"id":14979129,"url":"https://github.com/yotie/micron","last_synced_at":"2025-10-28T16:31:18.522Z","repository":{"id":40710787,"uuid":"210731108","full_name":"yotie/micron","owner":"yotie","description":null,"archived":false,"fork":false,"pushed_at":"2023-01-06T14:13:10.000Z","size":1624,"stargazers_count":5,"open_issues_count":39,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-09-29T02:22:42.725Z","etag":null,"topics":["hacktoberfest","serverless","vercel"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yotie.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/contributing.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-09-25T01:39:02.000Z","updated_at":"2020-11-02T13:24:12.000Z","dependencies_parsed_at":"2023-02-06T05:01:23.371Z","dependency_job_id":null,"html_url":"https://github.com/yotie/micron","commit_stats":null,"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yotie%2Fmicron","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yotie%2Fmicron/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yotie%2Fmicron/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yotie%2Fmicron/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yotie","download_url":"https://codeload.github.com/yotie/micron/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219859166,"owners_count":16556037,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","serverless","vercel"],"created_at":"2024-09-24T13:59:19.521Z","updated_at":"2025-10-28T16:31:18.072Z","avatar_url":"https://github.com/yotie.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cbr /\u003e\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://yotie.github.io/micron/assets/logo.svg\" alt=\"Logo\" style=\"margin-bottom: 50px\"\u003e\n  \u003cbr/\u003e\n  \u003cem\u003eA micro-framework for creating expressive and hyper-composable lambdas.\u003c/em\u003e\n\u003cp/\u003e\n\n\u003cbr/\u003e\u003cbr/\u003e\n\nWriting production-ready lambda services can require quite a bit of boilerplate. __micron__ is here to help improve that experience by providing powerful helpers that allow you to create expressive and hyper-composable serverless functions. This was designed to work seamlessly on [Vercel](https://vercel.app).\n  \u003c/p\u003e\n\u003c/p\u003e\n\n\u003cbr/\u003e\n\n## Getting Started\n\n### Setup\nInstall the package\n```sh\n$ yarn add @yotie/micron\n```\n\nCreate a simple lambda\n```js\nimport { micron } from '@yotie/micron';\n\nexport default micron(({ ok }: MicronParams) =\u003e {\n  return ok({ success: true, hello: 'world' });\n});\n```\n\n\n### Example Usage with contrast\n**BEFORE MICRON**\n```ts\nimport checkAuth from './checkAuth';\n\nexport default function(req: Request, res: Response) {\n  try {\n    if (!req.method.toUpperCase().equals('POST'))\n      return res.status(405).send('Method Unsupported');\n\n    const auth = checkAuth(req.headers['Authorization']);\n    if (!auth.isValid) return res.status(401).send('Unauthorized');\n\n    console.log('Logged in with', auth.user);\n    return res.status(200).json({\n      success: true,\n      user: auth.user,\n      body: req.body\n    });\n  } catch(err) {\n    return res.status(500).json({ success: false})\n  }\n}\n```\n**WITH MICRON**\n```js\nimport { createLambda, post } from '@yotie/micron';\nimport authMiddleWare from './auth';\n\nexport default createLambda(\n  post(({ req, body, ok, error }) =\u003e {\n      const { user } = req.auth;\n      console.log('Logged in with', user);\n\n      return ok({ success: true, body, user });\n  }),\n  { middlewares: [authMiddleWare, ...moreMiddleWare]}\n);\n```\n\u003e __micron__ improves the signal-to-noise ratio in your code which increases it readability, while reducing duplication and boilerplate.\n\n\u003c!-- ## Motivations\nTalks about some of the boilerplate and noise that typically get injected into lambda serverless function. mention how we're leveraging currying and functional composition which allows us to cleanly issolate and re-use various portions of our code and easily extend the functionality of our lambdas.  In the process of doing so, we also substantially improve the readability of our services while desing our functionality into highly cohesive and loosely coupled lambdas. The ultimate goal behind micron is to build a library that can be used to the build serverless functions on any serverles provider.\n\nWhile we currently support Vercel, our patterns should be compatible with AWS Lambda, Netlify, Firebase Functions, Toast\u003csup\u003ebeta\u003c/sup\u003e, and many more.\n\n\u003cbr/\u003e\n\n![diagram](docs/assets/diagram.png) --\u003e\n\n## API\n\n### `Type: MicronParams`\nVercel provides a [useful list of helpers](https://vercel.com/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers) inside of the Request and Response objects passed to the lambda. We've enhanced the experience a bit more by including an additional set of helpers, making it accessible via the `MicronParams` which is passed on to your functions. While leveraging __*micron*__, your serverless functions will change from the default method signature:\n```js\n(req: IncomingMessage, res: ServerResponse) =\u003e res: ServerResponse\n```\nto leveraging the `MicronLambda` function signature:\n```js\n(params: MicronParams) =\u003e res: ServerResponse\n```\n\n\n\nHere is a complete list of all the properties contained in the `MicronParams`:\n\n|Property|Type|Decription|\n|------|----|----------|\n|req | `Request` | The incoming Request object |\n|res | `Response` | The outgoing Response object|\n|body | `RequestBody` | An object containing the body sent by the request|\n|cookies | `RequestCookies` | An object containing the cookies sent by the request|\n|query | `RequestQuery` | An object containing the request's query string|\n|ok | `ResponseHelper` | Returns a __200__ HTTP response with your payload|\n|brotli | `ResponseHelper` | Returns a __200__ HTTP response with your payload compressed in `br` encoding|\n|badRequest | `ResponseHelper`| Returns a __400__ HTTP response with your payload|\n|unauthorized| `ResponseHelper`| Returns a __401__ HTTP response with your payload|\n|notFound |`ResponseHelper`|  Returns a __404__ HTTP response with your payload|\n|error| `ResponseHelper`| Returns a __500__ HTTP response with your payload|\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\nThe different `ResponseHelpers` are simple functions that allow you to return a ServerResponse with a preconfigured http status code. Leveraging these functions help enhance the readability and maintainability of your serverless projects by cutting down on some of the bloat. Instead of doing...\n```js\nreturn res.status(500).json({ message: 'Catastrophic Failure' });\n```\n...you can simplify your code to this:\n```js\nreturn error({ message: 'Catastrophic Failure' });\n```\n\nThese functions accept `String, Array, Object, Buffer` as valid inputs which will be passed on as the response body.\n\n\n\n### `micron(fn)`\nThe simplest way of creating a lambda is with the `micron` helper. This wraps your function in a global exception handler and will add light-weight request logging capabilites.\n\n#### Usage\n```js\nexport default micron(({ req, ok }: MicronParams) =\u003e {\n  return ok({\n    success: true,\n    requestType: req.method\n  });\n});\n```\n\u003e Note: lambdas created with the `micron` function accept requests from any HTTP method type. To restrict the HTTP method that your lambda allows, use one of the following: [get](#getfn), [post](#postfn), [put](#putfn), [patch](#patchfn), [del](#delfn)\n\n\n### `get(fn)`\n#### Usage\n```js\nimport { get } from '@yotie/micron';\n\nexport default get(({ ok }) =\u003e {\n  return ok({ success: true });\n});\n```\n\n\n### `post(fn)`\n#### Usage\n```js\nimport { post } from '@yotie/micron';\n\nexport default post(({ body, ok }) =\u003e {\n  return ok({ success: true, payload: body });\n});\n```\n\n\n### `put(fn)`\n#### Usage\n```js\nimport { put } from '@yotie/micron';\n\nexport default put(({ ok }) =\u003e {\n  return ok({ success: true });\n});\n```\n\n\n### `patch(fn)`\n#### Usage\n```js\nimport { patch } from '@yotie/micron';\n\nexport default patch(({ ok }) =\u003e {\n  return ok({ success: true });\n});\n```\n\n\n### `del(fn)`\n#### Usage\n```js\nimport { del } from '@yotie/micron';\n\nexport default del(({ ok }) =\u003e {\n  return ok({ success: true });\n});\n```\n\n### `match({})`\n\n#### Usage\n```ts\nimport { match } from '@yotie/micron';\n\nexport default match({\n  async post({ body, ok, error }) {\n    const user = await createUser(body);\n    return ok(user);\n  },\n  async get({ query, ok, notFound }) {\n    const user = await getUser(query.id);\n    if(!user?.id) return notFound();\n\n    return ok(user);\n  }\n})\n```\n\n\n\n### `createLambda(fn, opts)`\n#### Usage\n```ts\nimport { get } from '@yotie/micron';\nimport { traceMiddleware, } from './middlewares';\n\n\nexport default createLambda(\n  get(({ ok }) =\u003e {\n    // some business logic here\n    return ok({ success: true });\n  }),\n  {\n    cors: { origin: 'https://example.com, http://localhost:3000' },\n    middlewares: [traceMiddleware]\n  }\n);\n```\n\n#### __Parameters__\nName | Type | Default value |\n------ | ------ | ------ |\n`fn` | Lambda | - |\n`opts` | LambdaOptions | see defaults for *LambdaOptions*|\n\n\u003cbr/\u003e\n\n\n#### __LambdaOptions__\nName | Type | Default value |\n------ | ------ | ------ |\n`cors?` | CorsOptions | see defaults for *CorsOptions* |\n`middlewares?` | [MicronMiddleware](../interfaces/_src_createlambda_.micronmiddleware.md)[] | [] |\n\n\u003cbr/\u003e\n\n---\n## CORS\n\n#### __CorsOptions__\n|Parameter| type | default | Description|\n|---------|------|---------|------------|\n|origin| `string` | * | |\n|maxAge| `Number` | 86400 | |\n|allowMethods | `string[]` | [GET, PUT, POST, PATCH, DELETE, OPTIONS] | |\n|allowHeaders| `string[]`| [ X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept]| |\n|allowCredentials | `Boolean` | true | |\n|exposeHeaders| `string[]`| []| |\n\n\u003e Note: the origin can support multiple domains being set as well as glob patters\n\n---\n\n\n## Middlewares\nMiddleware functions are functions that have access to the request object (req) and the response object (res) to perform some task before the main lambda executes.\n\n- Execute any code.\n- Make changes to the request and the response objects.\n- End the request-response cycle, example: `return badRequest();`\n\n### `createMiddleware(fn, next)`\n\n#### Usage\n```js\nimport { createMiddleware } from '@yotie/micron';\n\nexport const auth = createMiddleware(({ req, unauthorized }, next) =\u003e {\n  const token = req.headers['Authorization'];\n  if (!token) return unauthorized();\n\n  req.auth = { user: 'exampleUser' }\n  console.log('User is allowed to access this lambda');\n\n  return next();\n});\n```\n\nYou can also use the micron helper to build out your middlewares w/o using the `createMiddleware` helper.\n\u003e Note: Middlewares must have the following signature `fn =\u003e (req, res) =\u003e fn(req, res)`\n\n```js\n//auth.js\n\nimport { micron, NowLambda } from '@yotie/micron';\nimport { isValid } from './_utils';\n\nconst auth = (lambda: NowLambda) =\u003e {\n  return micron({ req, res, body, unauthorized } =\u003e {\n    const token = req.headers['Authorization'];\n\n    if (!isValid(token)) return unautorized();\n\n    console.log('User is allowed to access this lambda');\n    return lambda(req, res);\n  });\n}\n\n```\n\n---\n\n## Testing\n\n```js\nimport { micron, mockLambda } from '@yotie/micron';\n\ntest('Successful api behaviour scenario', async () =\u003e {\n  const lambda = micron(({ ok }) =\u003e ok({ success: true }));\n  const { fetch } = await mockLambda(lambda);\n\n  const res = await fetch('?q=searchQuery');\n  const { success } = await res.json();\n\n  expect(res.ok).toBe(true);\n  expect(success).toBe(true);\n});\n```\n\n\n\n## TODO\n- [x] Create Logo ✅\n- [x] Create banner ✅\n- [ ] Documentation\n  - [x] Improve intro and Getting started ✅\n  - [ ] Motivation and design principles 🚧\n  - [x] Complete list of helpers from MicronParams ✅\n  - [ ] MicronHelpers and their scenarios 🚧\n    - [x] `micron` ✅\n    - [ ] `get` 🚧\n    - [ ] `put` 🚧\n    - [ ] `post` 🚧\n    - [ ] `del` 🚧\n    - [ ] `match` 🚧\n  - [ ] Document createLambda and use cases 🚧\n  - [x]  CORS and networking configuration ✅\n  - [ ]  Middlewares 🚧\n    - [x]  flexibility of our middleware pattern ✅\n  - [ ]  Testing and Mocking\n    - [x]  add query params serialization ✅\n  - [ ]  Contributing\n- [ ] Test more negative cases\n- [ ] Add file upload support\n- [ ] Split project into monorepo\n  - [ ] micron\n  - [ ] micron-mock\n  - [ ] micron-vercel\n  - [ ] micron-netlify\n  - [ ] micron-middleware-auth0\n  - [ ] micron-middleware-magiclink\n\n# Authors\n- Ashley Narcisse @darkfadr\n- Kennet Postigo @kennetpostigo\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyotie%2Fmicron","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyotie%2Fmicron","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyotie%2Fmicron/lists"}