Is it possible do define a global base path in hapi - javascript

I want every hapi route path to start with a prefix (/api/1) without adding it to each route. Is this possible?
The following route should be available with path /api/1/pets and not /pets
const Hapi = require('hapi');
const server = new Hapi.Server();
server.route({
method: 'GET',
path: '/pets'
})

Seems you can't do it globally for the whole application. But there's a possibility to add prefixes for all the routes defined inside a plugin:
server.register(require('a-plugin'), {
routes: {
prefix: '/api/1'
}
});
Hope this helps.
Just in case, if you're gonna try to add base path via events for new routes, it's not gonna work.

The best bet would be to use a constant in the paths -
server.route({
method: 'GET',
path: constants.route.prefix + '/pets')
});
and have the constant defined in a static constants.js file

I don't see such option in Hapi docs. Still, I can suggest you a small workaround. Make some function:
function createRoutePath(routePath) {
return `/api/1${routePath}`;
}
And then use it this way:
server.route({
method: 'GET',
path: createRoutePath('/pets')
});
UPDATE:
As another workaround, leave all as is, and setup proxy web server. For example nginx.

Related

Importing helper functions in Serverless

I want to import a helper function into a Node.js Lambda function in Serverless (AWS). I've tried using Layer functions, as well as a wrapper module for Serverless - but nothing has worked so far.
This is the function I want to use with other Lambda functions - helperFunc.js:
class HelperClass { ... } //a helper class that I want to use in other functions
module.exports = HelperClass
This is one of my Lambda functions. It also serves an API Gateway endpoint - users.js:
"use strict";
const helperClass = require('./helperFunc') //I don't know how to do this
module.exports.get = (event, context, callback) => {
const params = { ... } //DynamoDB Params
// a bunch of code that uses the helper class wrapper
callback(null, {
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
}, body: JSON.stringify(res), statusCode: 200})
}
};
This is what my serverless.yml currently looks like:
...
getUsers:
handler: src/users.get
events:
- http:
path: users
method: get
authorizer: authFunc
And this what my project directory looks like:
./
serverless.yml
./src
helperFunc.js
users.js
./auth
UPDATE 1: I was finally able to achieve this functionality using Lambda Layers. However, it still feels as if it's not the best way to do this mainly due to the complex directory set-up.
Here's the updated project directory:
./
serverless.yml
./layers/helperFunc/nodejs/node_modules/helperFunc
index.js
./src
users.js
./auth
And here is the updated serverless.yml file:
layers:
helperFunc:
path: layers/helperFunc
...
functions:
getUsers:
handler: src/users.get
layers:
- {Ref: HelperFuncLambdaLayer} # referencing the layer in cf
events:
- http:
path: users
method: get
authorizer: authFunc
The solution is to use serverless-webpack-plugin.

How to set proxy for different API server using Nuxt?

So I have 2 applications:
an Adonis API server accessible via http://10.10.120.4:3333
A SSR app using Nuxt.js accessible via http://10.10.120.4:80
The Nuxt.js app is accessible outside using url http://my-website.com. I have axios module with this config
axios: {
baseURL: '0.0.0.0:3333/api',
timeout: 5000
}
Now the problem is, when I am requesting data with asyncData it works, but when the request was made from outside asyncData, say created() for example, it throws an error saying the url http:0.0.0.0:3333 is missing which is true since it's already running in the browser and not in the server.
The first solution that I've tried is to change the baseURL of the axios module to this
axios: {
baseURL: 'http://my-website.com/api',
timeout: 5000
}
But it seems nuxt server can't find it, so I think the solution is to make proxy and installed #nuxtjs/proxy.
And this is my proxy config in nuxt.config.js
{
proxy: {
'/api': 'http://my-website.com:3333',
}
}
and then I just changed my axios baseURL to
http://my-website.com/api
But again it didn't work.
My question is, how do you deal with this kind of scenario? Accessing different server from browser?
When using Proxy in a nuxt project you need to remove baseUrl and set proxy to true as seen below.
axios: {
// Do away with the baseUrl when using proxy
proxy: true
},
proxy: {
// Simple proxy
"/api/": {
target: "https://test.com/",
pathRewrite: { "^/api/": "" }
}
},
when making a call to your endpoint do:
// append /api/ to your endpoints
const data = await $axios.$get('/api/users');
checkout Shealan article

Vue router on page refresh gets 404

I am using Vue router with history mode. On button click on the current page I route it to next page. On second page when i reload i get a 404. Is there a way to handle this in Vue and redirect it to home page.
export default new Router({
mode: "history",
routes: [
{
path: "/",
name: "first",
component: First
},
{
path: "/abc",
name: "abc",
component: Second,
props: true
},
you can use hash mode inested of history mode to resolve the problem on your router
let router = new Router({
mode: "hash",
routes: [
{
//and the urls with path on here ...
if any one of is facing the issue even after trying above solution, please find below method.
If you have vue.config.js which has
module.exports = {
publicPath: process.env.PUBLIC_URL || "", // <-- this is wrong
...
};
either remove the vue.config.js or try removing the publicPath from the exports object.
Also you can try below method if you dont want to remove the publicPath
module.exports = {
publicPath: process.env.PUBLIC_URL || "/", // <-- this is correct now (and default)
transpileDependencies: ["vuetify"],
};
This is related to how the history mode in Vue Router works. I have created a writeup about it, with a solution as well.
Depends on your server implementation you need to enable URL Rewrites there. Here's how this would be implemented using Express/Node.js:
const express = require('express');
const app = express();
const port = 80;
const buildLocation = 'dist';
app.use(express.static(`${buildLocation}`));
app.use((req, res, next) => {
if (!req.originalUrl.includes(buildLocation)) {
res.sendFile(`${__dirname}/${buildLocation}/index.html`);
} else {
next();
}
});
app.listen(port, () => console.info(`Server running on port ${port}`));
For more info, check out https://blog.fullstacktraining.com/404-after-refreshing-the-browser-for-angular-vue-js-app/. HTH
This usually happens, when you deploy the page to a hosting server. Check the official docs for more background info and specifiy tipps for different hosting entvironments
https://router.vuejs.org/guide/essentials/history-mode.html
We have resolved this on backend, we have filter where we intercept the request and redirect it to home page. We have made it configurable.

Templating in Electron?

Simple question here, but I found no useful resource. Is templating possible in Electron? Using Jade or Handlebars to display dynamic templates? I know there is .loadURL() that takes a static html file.
Is dynamic possible?
Thanks.
You could give electron-pug a chance. https://github.com/yan-foto/electron-pug
You can register a new buffer protocol via protocol.registerBufferProtocol.
main.js
var electron = require('electron');
var app = electron.app;
var protocol = electron.protocol;
var BrowserWindow = electron.BrowserWindow;
var pug = require('pug');
var window;
app.on('ready', function () {
// Define the `pug` scheme
protocol.registerBufferProtocol('pug', function (request, callback) {
var url = path.normalize(request.url.substr(7));
var content = pug.renderFile(url);
callback({
mimeType: 'text/html',
data: new Buffer(content)
});
});
window = new BrowserWindow({width: 600, height: 600});
// Load your file using the `pug` protocol
window.loadURL(url.format({
pathname: path.join(__dirname, 'index.pug'),
protocol: 'pug:',
slashes: true
}));
});
index.pug
html
head
title My title
body
h1 Hello world!
It would certainly be possible to use Jade or Handlebars for dynamic templating by running a local server in the Electron main process. I would not recommend this however, as it is kind of backwards. Electron is primarily a front end framework and while running a local server is good for some things, templating is not really one of them.
Most people use a frontend JS framework like Angular or React.
Probably too late to add here but thought it might be worthwhile. I have added a package to deal with adding views from any renderer and handle asset paths. So far I have just added the ejs renderer but plan on adding pug and haml as additional default renderers, but it is easy to extend and add your own as well. The package is called electron-view-renderer https://www.npmjs.com/package/electron-view-renderer
Hopefully this can help someone like it did our team. It is in its infancy, so all comments and contributions welcome
U can use ejs-electron to achieve the same purpose. U can check it out on github & simply install it as follows:
npm i ejs-electron --save
Just require it in ur main js file

How to add configuration settings to locals on Sails.js

I'm building a webapp using Sails.js and I'm wondering how to have different configurations on development and production modes. I thought that I just had to put a configuration key in config/local.js but it doesn't work. Here's an example of what I'm trying to do:
config: {
linkedIn_key: 'abcde',
linkedIn_secret: '13mcas',
linkedIn_url: 'http://localhost:1337/user/login'
}
I tried to access config in the UserController.js but I wasn't able to get the value. What is the right way to do it?
Best regards,
João
It should appear in sails.config. You can also try to create a new file: linkedin.js under the config folder and place your configurations there:
var linkedIn = {
key: 'abcde',
secret: '13mcas',
url: 'http://localhost:1337/user/login'
};
module.exports.linkedin = linkedIn;
and access it in your controller via
sails.config.linkedin

Categories