profile
viewpoint

gtsafas/mailgun.perl 8

Perl wrapper for mailgun

apcros/emoji-perl 6

A Perl interpreter for Emoji source code. (Yes. You read right)

keithbro/ember-fit-to-window-mixin 2

Maintains Ember.Component heights so that they fit vertically in the viewport.

keithbro/.NET-Library 0

.NET Library

keithbro/activerecord-repository 0

Implementation of the repository pattern for ActiveRecord, splitting domain model and persistence classes

keithbro/advent-of-code-2019 0

Solving Advent of Code 2019 in a different language every day!

PullRequestReviewEvent

Pull request review commentlux-group/lib-logger

DEVX-53: Updated documentation on logger migration.

 See [Creating Custom Formats](https://www.npmjs.com/package/winston#creating-cus The contextual logger uses Node's `async_hooks` functionality to add Request IDs to the log output.  ```ts-import { createContextualLogger } from '@luxuryescapes/lib-logger';+const {+  createContextualLogger+} = require("@luxuryescapes/lib-logger/lib/requestAwareLogger"); -const logger = createContextualLogger({ /*same args as createLogger*/ })+const loggerConfig = {+  logLevel: config.logLevel,+  service: config.herokuAppName,+  env: config.environment+};++const logger = createContextualLogger(loggerConfig);++module.exports = logger; ```+++## Migration existing project to lib-logger+Migrating existing project based on console.log to lib-logger can take a fair amount of effort even though it's not a hard work - just a lot of typing depending on the size of the project.++Below are the steps you need to take to successfully convert your project.++* Update following dependencies to the latest versions:+    * **@luxuryescapes/lib-logger** (required) This library keeps track of request context and formatting.+    * **@luxuryescapes/lib-authenticated-http-client** We use this library to make http calls and log related details+    including errors. It is crucial to make sure that this lib logs everything correctly in JSON format+    * **@luxuryescapes/lib-auth-middleware** All authentication is done by this library, which makes it really important to get correct logs from this lib.  +* Define logger, if not done already. You'll need to create a logger.js/ts file with content described above in "Contextual Logger" section.+* Add requestAware logger middleware. Add following to server.js/ts. +    ```ts+  // Imports  +  const requestAwareLogger = require("@luxuryescapes/lib-logger/lib/requestAwareLogger")+  +  // Middleware definitions+  app.use(requestAwareLogger.getMiddleware())+    ```+  * If your service uses **express.json()** or **bodyParser.json()** middleware you must set them before requestAwareLogger.+  * Make sure that you don't have **express.json()** or **bodyParser.json()** specified in your routes+    ```ts+    router.post(route, +      bodyParser.json(), // WILL NOT WORK. Remove it and replace with global express.json() middleware in server.js+      auth.cachedVerifyUser(), +      actions.actions.clone);+    ```+* Pass logger to lib-auth-middleware. +  ```ts+  const logger = require("../../logging/logger");+  const cachedVerifyUser = () => auth.verifyUser({ cache: redis, logger }); // Notice, logger+  ```  +* Pass logger to lib-authenticated-http-client.+  ````ts+  import logger from "../logging/logger";+  const authenticatedHttpClient = new AuthenticatedHttpClient({+      serviceName: config.herokuAppName,+      apiHost: config.hosts.api,+      serviceUsername: config.serviceUserEmail,+      servicePassword: config.serviceUserPassword,+      logRequests: true,+      timeRequests: true,+      logger: logger  // Notice, logger+  });+  ````+* Update all `console.log` with logger.info/warn/error. Winston logger works differently to console.log.+  So attention needs to be paid how to convert all console logs to the new format. Have a look at the examples below.+  They cover most of the scenarios.+    ````ts+    console.log("my message")+    logger.info("my message")+  +    const myVar = "var1"+    console.log("my var:", myVar)+    logger.info(`my var: ${myVar}`)+  +    const myError = new Error("error happened")+    console.log("Something went wrong", myError)+    logger.error("Something went wrong", myError) // will print "Something went wrong error happened" and append stacktrace as another field+  +    console.log("Request Body:", req.body)+    logger.info("Request Body", {requestBody: req.body})+  +    const varA = {a: 1, b: 2}+    const varB = "aaabbbccc"+    console.log("Params:", varA, varB)+    logger.info("Params", {params: {varA, varB}})+    ````+* Update .eslintrc.json to start throwing errors for console.log+    ```js+      "rules": {+        "prettier/prettier": "error",+        "no-undef": "error",+        "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],+        "no-unused-expressions": "error",+        "no-console": "error" // <===================+      },+    ```+* You can still live some console logs in scripts are not part of production code.

s/live/leave/

kostya-luxuryescape

comment created time in 3 days

Pull request review commentlux-group/lib-logger

DEVX-53: Updated documentation on logger migration.

 See [Creating Custom Formats](https://www.npmjs.com/package/winston#creating-cus The contextual logger uses Node's `async_hooks` functionality to add Request IDs to the log output.  ```ts-import { createContextualLogger } from '@luxuryescapes/lib-logger';+const {+  createContextualLogger+} = require("@luxuryescapes/lib-logger/lib/requestAwareLogger");

I don't love digging in to an external lib like this. To me, any exposes functions should be at the root level.

Also do we want to have a require example and an import example. import is the more modern way so feels wrong to document only the legacy approach .

kostya-luxuryescape

comment created time in 3 days

PullRequestReviewEvent
PullRequestReviewEvent

push eventlux-group/router

Keith Broughton

commit sha 8cd7bc969a161fbef36b918eefea61ae20ff2c10

Improve the error message when imports are bad

view details

push time in 3 days

push eventlux-group/router

Keith Broughton

commit sha 3fbee340ecb039c1e0d4117c766354e98c85a48b

2.5.2

view details

push time in 4 days

PullRequestReviewEvent

push eventlux-group/router

Keith Broughton

commit sha c8bfaaaf8643e90a3f0c5f1f3b43a1a916e2bf59

Handle syntax errors when generating types (#53)

view details

push time in 4 days

PR merged lux-group/router

Handle syntax errors when generating types

This handles the case where there is a JS error in your code and you try to generate types. The process is already resilient to TypeScript type errors.

+5 -1

0 comment

2 changed files

keithbro

pr closed time in 4 days

PR opened lux-group/router

Handle syntax errors when generating types

This handles the case where there is a JS error in your code and you try to generate types. The process is already resilient to TypeScript type errors.

+5 -1

0 comment

2 changed files

pr created time in 4 days

create barnchlux-group/router

branch : engx/better-error-handling

created branch time in 4 days

PR opened lux-group/router

Engx/force dev net log
+4 -4

0 comment

2 changed files

pr created time in 9 days

push eventlux-group/router

Keith Broughton

commit sha be566e28125c92ed18994154d28af47abc6ee7d6

Revert "Replaced .log logger method with .info for 3rd party logger compatibility. Automatically push network logging middleware in development environment" (#51) This reverts commit 1649bdf0ce1af4c25c4e2f827f9689af1d01ce52.

view details

push time in 9 days

PR merged lux-group/router

Revert "Replaced .log logger method with .info for 3rd party logger c…

…ompatibility. Automatically push network logging middleware in development environment"

Accidentally commited.

This reverts commit 1649bdf0ce1af4c25c4e2f827f9689af1d01ce52.

+6 -6

0 comment

2 changed files

keithbro

pr closed time in 9 days

PR opened lux-group/router

Revert "Replaced .log logger method with .info for 3rd party logger c…

…ompatibility. Automatically push network logging middleware in development environment"

Accidentally commited.

This reverts commit 1649bdf0ce1af4c25c4e2f827f9689af1d01ce52.

+6 -6

0 comment

2 changed files

pr created time in 9 days

create barnchlux-group/router

branch : task/revert-commit

created branch time in 9 days

PullRequestReviewEvent

pull request commentlux-group/router

Add authenticated request type

this is great, do you think we should make lib-auth-middleware a dependency of this lib? and automatically add it to the handlers if isPublic: false

I'm not sure why I didn't do this originally but could be cool

I think thats a good idea!

keithbro

comment created time in 11 days

push eventlux-group/router

Keith Broughton

commit sha a4b8becd155f794153c862f81aeaafb8d2baa91e

Add authenticated request type (#50)

view details

push time in 11 days

PR merged lux-group/router

Reviewers
Add authenticated request type

When you use the verifyUser Express middleware from lib-auth-middleware, it ensures an authenticated user is present and a couple of properties get added to the Request - user and jwt.

TypeScript doesn't recognise this and there are various awkward workarounds to make this work. This PR makes the user and jwt properties to be available automatically when used with auto generated types.

If a route is public, there will be a Cookie header in the OpenAPI schema and in the autogenerated types and this is trigger for the properties to be there.

So in your routes, if you say isPublic: true, the jwt and user properties will not be there, and when isPublic: false, the properties will be there.

Screen Shot 2022-01-11 at 9 08 40 pm

Screen Shot 2022-01-11 at 9 09 06 pm

+148 -18

0 comment

3 changed files

keithbro

pr closed time in 11 days

PullRequestReviewEvent

Pull request review commentlux-group/router

Add authenticated request type

+{+  "compilerOptions": {+    /* Visit https://aka.ms/tsconfig.json to read more about this file */++    /* Projects */+    // "incremental": true,                              /* Enable incremental compilation */+    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */+    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */+    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */+    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */+    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */++    /* Language and Environment */+    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */+    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */+    // "jsx": "preserve",                                /* Specify what JSX code is generated. */+    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */+    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */+    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */+    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */+    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */+    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */+    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */+    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */++    /* Modules */+    "module": "commonjs",                                /* Specify what module code is generated. */+    // "rootDir": "./",                                  /* Specify the root folder within your source files. */+    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */+    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */+    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */+    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */+    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */+    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */+    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */+    // "resolveJsonModule": true,                        /* Enable importing .json files */+    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */++    /* JavaScript Support */+    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */+    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */+    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */++    /* Emit */+    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */+    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */+    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */+    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */+    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */+    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */+    // "removeComments": true,                           /* Disable emitting comments. */+    // "noEmit": true,                                   /* Disable emitting files from a compilation. */+    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */+    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */+    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */+    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */+    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */+    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */+    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */+    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */+    // "newLine": "crlf",                                /* Set the newline character for emitting files. */+    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */+    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */+    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */+    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */+    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */+    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */++    /* Interop Constraints */+    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */+    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */+    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */+    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */+    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */++    /* Type Checking */+    "strict": true,                                      /* Enable all strict type-checking options. */+    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */+    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */+    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */+    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */+    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */+    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */+    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */+    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */+    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */+    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */+    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */+    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */+    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */+    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */+    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */+    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */+    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */+    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */++    /* Completeness */+    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */+    "skipLibCheck": false                                 /* Skip type checking all .d.ts files. */

Set this to false so that we can type check our index.d.ts file.

keithbro

comment created time in 11 days

PullRequestReviewEvent

Pull request review commentlux-group/router

Add authenticated request type

 declare module "@luxuryescapes/router" {     O extends keyof operations,     Response = operations[O]["responses"]   > = Response[keyof Response] extends Schema<infer S> ? S : never;++  type Jwt = {+    sub: string+    jti: string,+    iat: number,+    iss: string,+    exp: number,+    sut: boolean,+    roles: string[]+  }++  interface AuthenticatedRequest<P = ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = ParsedQs>+    extends ExpressRequest<P, ResBody, ReqBody, ReqQuery> {+      jwt: Jwt;+      user?: unknown; // optional because verifyUserSignature only sets jwt+    }      export interface Handler<     operations extends Record<string, any>,     O extends keyof operations,     R = ResBody<operations, O>,-    parameters = operations[O]["parameters"]+    parameters = operations[O]["parameters"],+    PathParams = parameters extends { path: any }+      ? parameters["path"]+      : Record<string, never>,+    ReqBody = parameters extends { body: { payload: any } }+      ? parameters["body"]["payload"]+      : Record<string, never>,+    Query = parameters extends { query: any }+      ? parameters["query"]+      : Record<string, never>,+    header = parameters extends { header: any } ?+      parameters['header']:+      Record<string, never>,+    Request = header extends { Cookie: any } ?

Here's the main part of the change

keithbro

comment created time in 11 days

Pull request review commentlux-group/router

Add authenticated request type

 declare module "@luxuryescapes/router" {     schema?: RouteSchema;     isPublic?: boolean;     preHandlers?: ExpressHandler[];-    handlers: RequestHandler<any, any, any, any>[];+    handlers: ((req: any, res: Response, next: NextFunction) => void)[]

I couldn't get req to type properly, so safety has been sacrificed here. This seems like a reasonable trade off because its unlikely that a handler would be typed incorrectly in this way.

keithbro

comment created time in 11 days

PullRequestReviewEvent

push eventlux-group/router

Keith Broughton

commit sha 78d9a8e0fc801af0b5e76a0a8f9cecd3af88be80

user is optional

view details

push time in 11 days

push eventlux-group/router

Keith Broughton

commit sha 101cfc7903d860289ee0c74dc40ad0dd345caba2

Remove blank line

view details

Keith Broughton

commit sha eecbe8cc28ebb8ecacfe14f897b6a3b68cef9e9a

Add missing dev deps

view details

Keith Broughton

commit sha 3b8bfbf476feeb0737c984fa2253c385bd5efd24

Add tsconfig

view details

push time in 11 days

more