loopback 4 use middleware prometheus-api-metrics - node.js

How can I use the prometheus within a LoopBack 4 application
here is a piece of code from the application.ts file
export class BackendV4Application extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
constructor(options?: ApplicationConfig)
{
options = { ...options, rest: { requestBodyParser: { json: { limit: '6mb' } } } };
super(options);
// Set up dotenv
dotenv.config();
// Set up the base path
this.basePath('/api');
this.api({
openapi: '3.0.0',
info: { title: pkg.name, version: pkg.version },
paths: {},
components: { securitySchemes: SECURITY_SCHEME_SPEC },
servers: [{ url: '/api' }]
});
this.setUpBindings();

There's a component package #loopback/metrics made by LoopBack that implements Prometheus. The Metrics collection for Prometheus documentation page explains how to set it up in the application.

Related

How to override the rollup output.format setting in vite?

I'm trying to solve the Vite build error I get:
RollupError: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.
The file name reported with this error points to
my web worker code, so I assumed that this setting belongs to the worker section in vite.config.ts:
import { defineConfig } from "vite";
import preact from "#preact/preset-vite";
import basicSsl from "#vitejs/plugin-basic-ssl";
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
import { NodeModulesPolyfillPlugin } from "#esbuild-plugins/node-modules-polyfill";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
export default defineConfig({
plugins: [
preact(),
basicSsl(),
],
server: {
port: 3001,
https: true,
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
worker: {
rollupOptions: {
output: {
format: "esm",
},
},
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
output: {
format: "esm",
},
},
},
});
Additionally, I set the output format in the build rollup options. However, neither of the two settings are applied and I still get the said error.
What is the correct way to change the rollup output format setting in Vite?
The worker output format must be specified directly in the worker config key, not its rollup options:
import { defineConfig } from "vite";
import preact from "#preact/preset-vite";
import basicSsl from "#vitejs/plugin-basic-ssl";
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
import { NodeModulesPolyfillPlugin } from "#esbuild-plugins/node-modules-polyfill";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
export default defineConfig({
plugins: [
preact(),
basicSsl(),
],
server: {
port: 3001,
https: true,
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
worker: {
format: "es",
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
output: {
format: "esm",
},
},
},
});

Quasar-cli-vite devServer proxy not working

I'm starting to test Quasar framework and I want to proxy some url to my local backend but the configuration doesn't seem to work (documentation here).
The part of my quasar.config.js where the proxy should be configured:
devServer: {
// https: true
proxy: {
'/association': {
target: 'http://localhost:8080',
changeOrigin: true,
}
},
open: false,
},
I've also tried to do it inline '/association': 'http://localhost:8080' with the same result. My request are not redirect and query on port 80: http://localhost/association/setProducerStats
Anyone already managed to configure the proxy ?
Quasar is already running itself on port 8080 - try to use a different port for your local backend, or add port: 8090 to the devServer config.
Example config for Vite:
// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'path';
import vue from '#vitejs/plugin-vue';
import { quasar, transformAssetUrls } from '#quasar/vite-plugin';
import viteStylelint from './plugins/stylelint';
import eslintPlugin from 'vite-plugin-eslint';
import Components from 'unplugin-vue-components/vite';
import { QuasarResolver } from 'unplugin-vue-components/resolvers';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue({
template: { transformAssetUrls }
}),
quasar({
autoImportComponentCase: 'pascal',
sassVariables: 'src/quasar-variables.sass'
}),
viteStylelint({
exclude: /node_modules|.*uno\.css/
}),
eslintPlugin({
cache: false
}),
Components({
resolvers: [QuasarResolver()],
include: [/\.vue$/],
exclude: [/node_modules/, /\.git/, /\.nuxt/],
})
],
resolve: {
alias: {
src: resolve(__dirname, './src'),
'#': resolve(__dirname, './src'),
},
},
server: {
https: false,
port: 9000,
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
secure: true,
//rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
build: {
terserOptions: {
compress: {
drop_console: true,
},
},
// reportCompressedSize: true,
chunkSizeWarningLimit: 1024,
rollupOptions: {
output: {
manualChunks(id)
{
if (id.includes('/node_modules/'))
{
const modules = ['quasar', '#quasar', 'vue', '#vue'];
const chunk = modules.find((module) => id.includes(`/node_modules/${module}`));
return chunk ? `vendor-${chunk}` : 'vendor';
}
},
},
},
},
});

Next JS advanced feature Content Security policy format

I am adding security Policy headers to my application using Security headers advanced feature of next.js
Reference :https://nextjs.org/docs/advanced-features/security-headers
I am quiet clear of how to add the security policies to the next application except the Content Security policy,It does not show any format of the policy in the Documentation :
Taking help of next and developer.mozilla org I have some code in place,that I am attaching herewith. Can anybody help me with the correct format to define content-security policy in Next.JS
Code in Next.config.js
const cspPolicy = "default-src 'self';connect-src 'self','preview.contentful.com','*.flippenterprise.net', 'aq.flippenterprise.net','https://www.google-analytics.com','dpm.demdex.net','stats.g.doubleclick.net','lcljoefresh.sc.omtrdc.net','sfml.flippback.com','p.flipp.com','https://sentry.io/',";
const securityHeaders = [
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'Content-Security-Policy',
value: cspPolicy
}
];
const headers = {
async headers() {
return [
{
// Apply these headers to all routes in your application.
source: '/(.*)',
headers: securityHeaders,
},
]
},
}
const nextConfig = {
env: {
search_key: process.env.search_key,
appDynamicsKey: process.env.appDynamicsKey,
ENVIRONMENT: process.env.ENVIRONMENT,
},
webpack5:false,
// https://nextjs.org/docs#customizing-webpack-config
webpack: (webpackConfig) => {
const { module = {} } = webpackConfig;
return {
...webpackConfig,
module: {
...module,
rules: [
...(module.rules || []),
{
test: /\.(txt|png|woff|woff2|eot|ttf|gif|jpg|ico|svg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name]_[hash].[ext]',
publicPath: '/_next/static/files',
outputPath: 'static/files',
},
},
},
{
test: /\.spec.jsx$/,
loader: 'ignore-loader',
},
],
},
};
},
};
const sassOptions = {
sassLoaderOptions: {
outputStyle: 'compressed',
},
};
module.exports = withPlugins(
[[withSass, sassOptions], [withFonts], [withCSS], [withBundleAnalyzer]],
nextConfig,
headers,
);

How to put route aliases in the individual service settings instead of the API gateway service in Molecular

As mentioned in the documentation route aliases can be put in the API service, but I want to put the aliases in the individual service settings, how can I do that?
Let's say I have a users service and API gateway,
and the users service have a role action and it will just send back the id as an example
If I send a get request to /users/role/1 I will get 1 as result
It works like this
api.service.js
"use strict";
const ApiGateway = require("moleculer-web");
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [{
path: "/api",
whitelist: [
// Access to any actions in all services under "/api" URL
"**"
],
aliases: {
"GET users/role/:uid": "users.role"
}
}],
// Serve assets from "public" folder
assets: {
folder: "public"
},
},
};
users.service.js
"use strict";
module.exports = {
name: "users",
/**
* Service settings
*/
settings: {},
/**
* Actions
*/
actions: {
role: {
cache: {
keys: ["uid"]
},
rest: "GET role/:uid",
handler(ctx) {
return ctx.params.uid
}
}
},
};
wanted somthing like this
api.service.js
"use strict";
const ApiGateway = require("moleculer-web");
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [{
path: "/api",
whitelist: [
// Access to any actions in all services under "/api" URL
"**"
]
}],
// Serve assets from "public" folder
assets: {
folder: "public"
},
},
};
users.service.js
"use strict";
module.exports = {
name: "users",
/**
* Service settings
*/
settings: {
routes: [{
path: "/",
aliases: {
"GET role/:uid": "role"
}
}],
},
/**
* Actions
*/
actions: {
role: {
cache: {
keys: ["uid"]
},
rest: "GET role/:uid",
handler(ctx) {
return ctx.params.uid
}
}
},
};
the goal is that every service is separated in its own project and the aliases for any service can be put in it and not in the API service
// api.service.js
module.exports = {
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [
{
path: "/",
whitelist: [
"users.**"
],
autoAliases: true
}
]
}
};
// users.service.js
module.exports = {
name: "users",
settings: {
// Base path
rest: "users/"
},
actions: {
role: {
cache: {
keys: ["uid"]
},
rest: "GET role/:uid",
handler(ctx) {
return ctx.params.uid
}
}
}
};

how to access to globals in pug render

i am using fastify with point-of-view module to render pug templates:
Fastify.register(require('point-of-view'), {
engine: {
pug: require('pug')
},
templates: Path.join(__dirname,'templates'),
options: {
filename: Path.join(__dirname,'templates/layout.pug'),
globals: [
{
assets_path: 'Path_to_assets'
}
]
}
})
how I can access to globals inside pug templates?
well, I found a method: accessing to env vars.
in my templates I use
global.process.env.ASSETS_PATH
where ASSETS_PATH is declared as part of my env vars
You can't access 'options' parameter. But you can pass your variable via defaultContext like this:
fastify.register(require('point-of-view'), {
engine: {
pug: require('pug')
},
defaultContext: {
// Place your variable here
globals: [],
myVars,
appName: 'Fastify Website'
},
templates: Path.join(__dirname,'templates'),
options: {
filename: Path.join(__dirname,'templates/layout.pug'),
globals: [
{
assets_path: 'Path_to_assets'
}
]
}
})

Resources