Skip to content

Commit

Permalink
Merge pull request #123 from IKatsuba/feature/express-cache
Browse files Browse the repository at this point in the history
Feature/express cache
  • Loading branch information
IKatsuba authored Feb 10, 2021
2 parents f411ede + 341799a commit 2192570
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 30 deletions.
34 changes: 7 additions & 27 deletions apps/rickandmorty/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';
import { Request } from 'express';
import { LRUCache } from '@ngx-ssr/cache';
import { withCache } from '@ngx-ssr/cache/express';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const cache = new LRUCache({ maxAge: 10 * 60_000, maxSize: 100 });

const server = express();
const distFolder = join(process.cwd(), 'dist/apps/rickandmorty/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
Expand All @@ -24,30 +22,12 @@ export function app(): express.Express {
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine(
'html',
async (
filePath: string,
options: { req: Request },
callback: (
err?: Error | null | undefined,
html?: string | undefined
) => void
) => {
const fromCache = await cache.get(options.req.originalUrl).toPromise();

if (fromCache) {
callback(null, fromCache);
} else {
ngExpressEngine({
bootstrap: AppServerModule,
})(filePath, options, async (err, html) => {
if (!err) {
await cache.set(options.req.originalUrl, html).toPromise();
}

callback(err, html);
});
}
}
withCache(
new LRUCache({ maxAge: 10 * 60_000, maxSize: 100 }),
ngExpressEngine({
bootstrap: AppServerModule,
})
)
);

server.set('view engine', 'html');
Expand Down
54 changes: 54 additions & 0 deletions libs/ngx-ssr/cache/express/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { CacheController } from '@ngx-ssr/cache';

export type ExpressRenderEngine = (
filePath: string,
options: { req: { originalUrl: string }; [key: string]: any },
callback: (err?: Error | null | undefined, html?: string | undefined) => void
) => void;

export function withCache(
cache: CacheController,
engine: ExpressRenderEngine
): ExpressRenderEngine {
return (
filePath: string,
options: { req: { originalUrl: string }; [key: string]: any },
callback: (
err?: Error | null | undefined,
html?: string | undefined
) => void
) => {
function runEngine() {
engine(filePath, options, async (err, html) => {
if (!err && originalUrl) {
try {
await cache.set(originalUrl, html).toPromise();
} catch (e) {
console.error(`Setting cache for url ${originalUrl} is failed`, e);
}
}

callback(err, html);
});
}

const originalUrl = options.req?.originalUrl;

if (!originalUrl) {
runEngine();
return;
}

cache
.get(originalUrl)
.toPromise()
.then((fromCache) => {
if (fromCache) {
callback(null, fromCache);
} else {
runEngine();
}
})
.catch(runEngine);
};
}
5 changes: 5 additions & 0 deletions libs/ngx-ssr/cache/express/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lib": {
"entryFile": "index.ts"
}
}
2 changes: 1 addition & 1 deletion libs/ngx-ssr/cache/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
displayName: 'ngx-ssr-cache',
preset: '../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
setupFilesAfterEnv: ['<rootDir>/test-setup.ts'],
globals: {
'ts-jest': {
tsConfig: '<rootDir>/tsconfig.spec.json',
Expand Down
File renamed without changes.
3 changes: 2 additions & 1 deletion libs/ngx-ssr/cache/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"strictMetadataEmit": true,
"enableResourceInlining": true
},
"exclude": ["src/test-setup.ts", "**/*.spec.ts"],
"exclude": [
"test-setup.ts", "**/*.spec.ts"],
"include": ["**/*.ts"]
}
4 changes: 3 additions & 1 deletion libs/ngx-ssr/cache/tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"files": [
"test-setup.ts"
],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"baseUrl": ".",
"paths": {
"@ngx-ssr/cache": ["libs/ngx-ssr/cache/src/index.ts"],
"@ngx-ssr/cache/*": ["libs/ngx-ssr/cache/*"],
"ngx-rickandmorty": ["libs/rickandmorty/api/src/index.ts"],
"@ngx-ssr/rickandmorty/utils": ["libs/rickandmorty/utils/src/index.ts"],
"@ngx-ssr/timeout": ["libs/ngx-ssr/timeout/src/index.ts"],
Expand Down

0 comments on commit 2192570

Please sign in to comment.