Skip to content

Instantly share code, notes, and snippets.

@cchamplin
Created March 31, 2020 19:06
Show Gist options
  • Select an option

  • Save cchamplin/c55778d4a70854a5d72bab2a8c4450fe to your computer and use it in GitHub Desktop.

Select an option

Save cchamplin/c55778d4a70854a5d72bab2a8c4450fe to your computer and use it in GitHub Desktop.

Revisions

  1. cchamplin created this gist Mar 31, 2020.
    55 changes: 55 additions & 0 deletions offline-invalidate.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    const HandlerRunner = require("serverless-offline/dist/lambda/handler-runner/index").default;

    class OfflineInvalidate {
    constructor(serverless, options) {
    this.serverless = serverless;
    this.hooks = {
    "before:offline:start:init": (opts) => this.inject()
    };
    this.lastRunner = {};
    }
    cacheInvalidation(filePath) {
    if (require.cache[require.resolve(filePath)]) {
    delete require.cache[require.resolve(filePath)];
    }
    }
    findPrivateProperty(obj, propName) {
    const props = Object.getOwnPropertyNames(obj);
    for (let prop of props) {
    if (prop.indexOf(`_${propName}`) > 0) {
    return prop;
    }
    }
    return null;
    }
    inject() {
    const that = this;
    const oldRun = HandlerRunner.prototype.run;
    let run = async function(event, context) {
    const runnerPropName = that.findPrivateProperty(this, 'runner');
    const funOptionsPropName = that.findPrivateProperty(this, 'funOptions');
    if (!runnerPropName || !funOptionsPropName) {
    return oldRun(event, context);
    }

    const runner = this[runnerPropName];
    const funOptions = this[funOptionsPropName];
    const internalRef = funOptions.handlerPath || funOptions.handler;

    if (that.lastRunner[internalRef]) {
    await that.lastRunner[internalRef].cleanup();
    }

    that.cacheInvalidation(internalRef);

    const runnerInstance = this[runnerPropName] = await this._loadRunner();

    that.lastRunner[internalRef] = runnerInstance;

    return runnerInstance.run(event, context);
    }
    HandlerRunner.prototype.run = run;
    }
    }

    module.exports = OfflineInvalidate