@spytecgps/lambda-utils 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ import { APIGatewayProxyResult } from 'aws-lambda';
2
+ import { WrapperArgs } from './types';
3
+ declare const apiGwWrapper: <E, R>({ event, schema, handler }: WrapperArgs<E, R>) => Promise<APIGatewayProxyResult>;
4
+ export default apiGwWrapper;
@@ -0,0 +1,3 @@
1
+ export default class UnauthorizedError extends Error {
2
+ code: number;
3
+ }
@@ -1,3 +1,4 @@
1
1
  import BadRequestError from './BadRequestError';
2
2
  import NotFoundError from './NotFoundError';
3
- export { BadRequestError, NotFoundError };
3
+ import UnauthorizedError from './UnauthorizedError';
4
+ export { BadRequestError, NotFoundError, UnauthorizedError };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import wrapper from './wrapper';
1
+ import apiGwWrapper from './apiGwWrapper';
2
2
  import * as errors from './errors';
3
- export { wrapper, errors };
3
+ export { apiGwWrapper, errors };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof exports?exports["jarvis-events-sdk"]=r():e["jarvis-events-sdk"]=r()}(global,(function(){return function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";t.r(r),t.d(r,"wrapper",(function(){return a})),t.d(r,"errors",(function(){return n}));var n={};t.r(n),t.d(n,"BadRequestError",(function(){return o})),t.d(n,"NotFoundError",(function(){return s}));class o extends Error{constructor(){super(...arguments),this.code=400}}class s extends Error{constructor(){super(...arguments),this.code=404,this.message="Not found"}}const u={"Content-Type":"application/json"},c=(e,r,t)=>{const n=((e,r,t)=>({success:e<400,message:r,result:t}))(e,r,t);return{headers:Object.assign({},u),statusCode:e,body:n&&JSON.stringify(n)}};var a=async({event:e,schema:r,handler:t})=>{console.log("wrapper - got event",e);try{const{error:n,value:s}=((e,r)=>e.validate(r,{allowUnknown:!0,errors:{label:"key",wrap:{label:!1}}}))(r,e);if(n)throw new o(n.message);const u=await t(s);return c(200,"ok",u)}catch(e){return console.error("wrapper - caught error",e),c(e.code||500,e.message||"Error")}}}])}));
1
+ !function(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof exports?exports["jarvis-events-sdk"]=r():e["jarvis-events-sdk"]=r()}(global,(function(){return function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";t.r(r),t.d(r,"apiGwWrapper",(function(){return d})),t.d(r,"errors",(function(){return n}));var n={};t.r(n),t.d(n,"BadRequestError",(function(){return u})),t.d(n,"NotFoundError",(function(){return a})),t.d(n,"UnauthorizedError",(function(){return i}));const o={"Content-Type":"application/json"},s=({statusCode:e=200,message:r="ok",data:t,headers:n={}})=>{const s=((e,r,t)=>({success:e<400,message:r,result:t||void 0}))(e,r,t);return{headers:Object.assign(Object.assign({},o),n),statusCode:e,body:s&&JSON.stringify(s)}};class u extends Error{constructor(){super(...arguments),this.code=400}}class a extends Error{constructor(){super(...arguments),this.code=404,this.message="Not found"}}class i extends Error{constructor(){super(...arguments),this.code=401}}var c=(e,r)=>{if(!r)return console.warn("skipping validation"),e;const{error:t,value:n}=r.validate(e,{allowUnknown:!0,errors:{label:"key",wrap:{label:!1}}});if(t)throw new u(t.message);return n};var d=async({event:e,schema:r,handler:t})=>{console.log("apiGwWrapper - got event",e);try{const n=c(e,r),o=await t(n);return console.log("apiGwWrapper - finished",o),s(o)}catch(e){return console.error("apiGwWrapper - caught error",e),s({statusCode:e.code||500,message:e.message||"Error"})}}}])}));
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["webpack://jarvis-events-sdk/webpack/universalModuleDefinition","webpack://jarvis-events-sdk/webpack/bootstrap","webpack://jarvis-events-sdk/./src/errors/BadRequestError.ts","webpack://jarvis-events-sdk/./src/errors/NotFoundError.ts","webpack://jarvis-events-sdk/./src/response.ts","webpack://jarvis-events-sdk/./src/wrapper.ts"],"names":["root","factory","exports","module","define","amd","global","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","BadRequestError","Error","code","NotFoundError","message","baseHeaders","buildResponse","data","resp","success","result","apiResponse","headers","statusCode","body","JSON","stringify","async","event","schema","handler","console","log","error","validatedEvent","validate","allowUnknown","errors","label","wrap","doValidation","err"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAQ,qBAAuBD,IAE/BD,EAAK,qBAAuBC,IAR9B,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,I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M,SAASP,EAAO,CACrBQ,cAAc,EACdC,OAAQ,CACNC,MAAO,MACPC,KAAM,CACJD,OAAO,MAQ8BE,CAAgBX,EAAQD,GACjE,GAAIK,EACF,MAAM,IAAIvB,EAAgBuB,EAAMnB,SAElC,MAAMM,QAAeU,EAAQI,GAC7B,OAAOlB,EAAc,IAAK,KAAMI,GAChC,MAAOqB,GAEP,OADAV,QAAQE,MAAM,yBAA0BQ,GACjCzB,EAAeyB,EAAI7B,MAAmB,IAAK6B,EAAI3B,SAAW","file":"index.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"jarvis-events-sdk\"] = factory();\n\telse\n\t\troot[\"jarvis-events-sdk\"] = factory();\n})(global, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export default class BadRequestError extends Error {\r\n code = 400;\r\n}\r\n","export default class NotFoundError extends Error {\r\n code = 404;\r\n message = 'Not found';\r\n}\r\n","export const apiResponse = <T>(code: number, message: string, data?: T) => {\r\n return {\r\n success: code < 400,\r\n message,\r\n result: data,\r\n };\r\n};\r\n\r\nconst baseHeaders = {\r\n 'Content-Type': 'application/json',\r\n};\r\n\r\nexport const buildResponse = (code: number, message: string, data?: any) => {\r\n const resp = apiResponse(code, message, data);\r\n return {\r\n headers: { ...baseHeaders },\r\n statusCode: code,\r\n body: resp && JSON.stringify(resp),\r\n };\r\n};\r\n","import { APIGatewayProxyResult } from 'aws-lambda';\r\nimport { ObjectSchema } from 'joi';\r\nimport { BadRequestError } from './errors';\r\nimport { buildResponse } from './response';\r\nimport { FullValidationResult, WrapperArgs } from './types';\r\n\r\nconst doValidation = <T>(schema: ObjectSchema<T>, event): FullValidationResult<T> =>\r\n schema.validate(event, {\r\n allowUnknown: true,\r\n errors: {\r\n label: 'key',\r\n wrap: {\r\n label: false,\r\n },\r\n },\r\n }) as FullValidationResult<T>;\r\n\r\nconst wrapper = async <T, R = any>({ event, schema, handler }: WrapperArgs<T, R>): Promise<APIGatewayProxyResult> => {\r\n console.log(`wrapper - got event`, event);\r\n try {\r\n const { error, value: validatedEvent } = doValidation<T>(schema, event);\r\n if (error) {\r\n throw new BadRequestError(error.message);\r\n }\r\n const result = await handler(validatedEvent);\r\n return buildResponse(200, 'ok', result);\r\n } catch (err) {\r\n console.error(`wrapper - caught error`, err);\r\n return buildResponse((err.code as number) || 500, err.message || 'Error');\r\n }\r\n};\r\n\r\nexport default wrapper;\r\n"],"sourceRoot":""}
1
+ {"version":3,"sources":["webpack://jarvis-events-sdk/webpack/universalModuleDefinition","webpack://jarvis-events-sdk/webpack/bootstrap","webpack://jarvis-events-sdk/./src/response.ts","webpack://jarvis-events-sdk/./src/errors/BadRequestError.ts","webpack://jarvis-events-sdk/./src/errors/NotFoundError.ts","webpack://jarvis-events-sdk/./src/errors/UnauthorizedError.ts","webpack://jarvis-events-sdk/./src/validation/validateEvent.ts","webpack://jarvis-events-sdk/./src/apiGwWrapper.ts"],"names":["root","factory","exports","module","define","amd","global","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","baseHeaders","buildProxyResult","statusCode","message","data","headers","resp","success","result","undefined","buildResponseBody","body","JSON","stringify","BadRequestError","Error","code","NotFoundError","UnauthorizedError","event","schema","console","warn","error","validate","allowUnknown","errors","label","wrap","async","handler","log","validatedEvent","err"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAQ,qBAAuBD,IAE/BD,EAAK,qBAAuBC,IAR9B,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBX,OAAOC,eAAeU,EAA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EAAMpB,SAElC,OAAOlB,GCAM,MAhBM4C,OAAeV,QAAOC,SAAQU,cACjDT,QAAQU,IAAI,2BAA4BZ,GACxC,IACE,MAAMa,EAAiB,EAAiBb,EAAOC,GACzCZ,QAAesB,EAAQE,GAE7B,OADAX,QAAQU,IAAI,0BAA2BvB,GAChCP,EAAoBO,GAC3B,MAAOyB,GAEP,OADAZ,QAAQE,MAAM,8BAA+BU,GACtChC,EAAoB,CACzBC,WAAa+B,EAAIjB,MAAmB,IACpCb,QAAS8B,EAAI9B,SAAW","file":"index.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"jarvis-events-sdk\"] = factory();\n\telse\n\t\troot[\"jarvis-events-sdk\"] = factory();\n})(global, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","import { HandlerResponse } from './types';\nimport { APIGatewayProxyResult } from 'aws-lambda';\n\nconst baseHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const buildResponseBody = <T>(\n statusCode: number,\n message: string,\n data?: T,\n): {\n success: boolean;\n message: string;\n result: T | undefined;\n} => {\n return {\n success: statusCode < 400,\n message,\n result: data ? data : undefined,\n };\n};\n\nexport const buildProxyResult = <R>({\n statusCode = 200,\n message = 'ok',\n data,\n headers = {},\n}: HandlerResponse<R>): APIGatewayProxyResult => {\n const resp = buildResponseBody<R>(statusCode, message, data);\n return {\n headers: { ...baseHeaders, ...headers },\n statusCode,\n body: resp && JSON.stringify(resp),\n };\n};\n","export default class BadRequestError extends Error {\r\n code = 400;\r\n}\r\n","export default class NotFoundError extends Error {\r\n code = 404;\r\n message = 'Not found';\r\n}\r\n","export default class UnauthorizedError extends Error {\n code = 401;\n}\n","import { ObjectSchema } from 'joi';\nimport { BadRequestError } from '../errors';\n\nconst validateEvent = <T>(event: any, schema?: ObjectSchema<T>): T => {\n if (!schema) {\n console.warn(`skipping validation`);\n return event as T;\n }\n\n const { error, value } = schema.validate(event, {\n allowUnknown: true,\n errors: {\n label: 'key',\n wrap: {\n label: false,\n },\n },\n });\n if (error) {\n throw new BadRequestError(error.message);\n }\n return value as T;\n};\n\nexport default validateEvent;\n","import { APIGatewayProxyResult } from 'aws-lambda';\nimport { buildProxyResult } from './response';\nimport { WrapperArgs } from './types';\nimport validateEvent from './validation/validateEvent';\n\nconst apiGwWrapper = async <E, R>({ event, schema, handler }: WrapperArgs<E, R>): Promise<APIGatewayProxyResult> => {\n console.log(`apiGwWrapper - got event`, event);\n try {\n const validatedEvent = validateEvent<E>(event, schema);\n const result = await handler(validatedEvent);\n console.log(`apiGwWrapper - finished`, result);\n return buildProxyResult<R>(result);\n } catch (err) {\n console.error(`apiGwWrapper - caught error`, err);\n return buildProxyResult<R>({\n statusCode: (err.code as number) || 500,\n message: err.message || 'Error',\n });\n }\n};\n\nexport default apiGwWrapper;\n"],"sourceRoot":""}
@@ -1,12 +1,8 @@
1
- export declare const apiResponse: <T>(code: number, message: string, data?: T) => {
1
+ import { HandlerResponse } from './types';
2
+ import { APIGatewayProxyResult } from 'aws-lambda';
3
+ export declare const buildResponseBody: <T>(statusCode: number, message: string, data?: T) => {
2
4
  success: boolean;
3
5
  message: string;
4
6
  result: T;
5
7
  };
6
- export declare const buildResponse: (code: number, message: string, data?: any) => {
7
- headers: {
8
- 'Content-Type': string;
9
- };
10
- statusCode: number;
11
- body: string;
12
- };
8
+ export declare const buildProxyResult: <R>({ statusCode, message, data, headers, }: HandlerResponse<R>) => APIGatewayProxyResult;
package/dist/types.d.ts CHANGED
@@ -1,18 +1,27 @@
1
1
  import { APIGatewayProxyWithLambdaAuthorizerEvent } from 'aws-lambda';
2
- import { ObjectSchema, ValidationResult } from 'joi';
2
+ import { ObjectSchema } from 'joi';
3
+ export interface SpytecAuthorizedResources {
4
+ devices: string[];
5
+ }
3
6
  export interface SpytecAuthContext {
4
7
  type: 'user' | 'client';
5
8
  userId?: string;
6
9
  clientId: number;
7
- resources: {
8
- devices: string[];
9
- };
10
+ resources: SpytecAuthorizedResources;
10
11
  }
11
- export interface WrapperArgs<T, R> {
12
- event: APIGatewayProxyWithLambdaAuthorizerEvent<SpytecAuthContext>;
13
- schema: ObjectSchema<T>;
14
- handler: (event: T) => Promise<R>;
12
+ declare type BaseEvent = APIGatewayProxyWithLambdaAuthorizerEvent<SpytecAuthContext>;
13
+ export interface WrapperArgs<E, R> {
14
+ event: BaseEvent;
15
+ schema?: ObjectSchema<E>;
16
+ handler: (event: E) => Promise<HandlerResponse<R>>;
15
17
  }
16
- export interface FullValidationResult<T> extends Omit<ValidationResult, 'value'> {
17
- value: T;
18
+ export interface HandlerResponse<R> {
19
+ statusCode?: number;
20
+ headers?: {
21
+ [header: string]: boolean | number | string;
22
+ };
23
+ isBase64Encoded?: boolean;
24
+ message?: string;
25
+ data?: R;
18
26
  }
27
+ export {};
@@ -0,0 +1 @@
1
+ export declare const json: any;
@@ -0,0 +1,3 @@
1
+ import { ObjectSchema } from 'joi';
2
+ declare const validateEvent: <T>(event: any, schema?: ObjectSchema<T>) => T;
3
+ export default validateEvent;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spytecgps/lambda-utils",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Lambda Utils",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",