hapipal / boilerplate Goto Github PK
View Code? Open in Web Editor NEWA friendly, proven starting place for your next hapi plugin or deployment
Home Page: https://hapipal.com
A friendly, proven starting place for your next hapi plugin or deployment
Home Page: https://hapipal.com
The readme needs to be cleaned-up a bit. Also worth describing some ideas around plugin/server separation and why the boilerplate is constructed the way it's constructed.
Lab has made some changes to its linting strategy in order to support ecma syntax available in node v12, e.g. class fields, and we should make comparable fixes to the the default eslintrc used by the boilerplate. Here is the relevant fix in lab hapijs/lab@9d925d4
After creating a project with hpal new
, how can I bring in a flavor, for example docker
or swagger
?
Hi,
I just stumbled upon your boilerplate -- is there anything you'd do differently since this was last updated?
Cheers!
I saw that you offer knex
and objection
support but what do you think of adding Sequelize support as flavor as well?
I could definitely look into making a PR if that's something you'd consider.
Thanks for the great project.
Could you comment a bit, in your opinion, what should the plugins and methods directories contain.
Methods are route handlers? And plugins should contain code for modules that are not route handlers?
Maybe update tutorial a bit.
It should say what each one does instead of having to click on each projects link and read through their stuff.
In that you could have recipes so mixing flavors makes something of common request. Example
Vanilla + Eggs + Ice + sugar = make Magic server that generates chill QR codes I guesses like
Not really clear, I would like to have a hapi with
Is it possible to just run all flavors on top of each other ?
The line
await HauteCouture.using()(server, options);
results in
Error: "schwifty" is not a method on the passed server.
when trying to npm start
or npm test
.
The fix is to replace that call with
await HauteCouture.using();
as per hapipal-realworld-example-app.
We want policies! See: https://github.com/mark-bradshaw/mrhorse
I've set up a project using the docs guide and I have a route set up like so
{
method: 'POST',
path: '/',
options: {
validate: {
payload: {
name: Joi.string().required()
}
},
handler: async (request, h) => {
}
}
}
However this throws an error
Error: server.route() called by haute using /api/lib/routes/parent.js: Cannot set uncompiled validation rules without configuring a validator
This makes sense because unlike the Schwifty models, the mongoose models don't have Joi validation integrated. Can the documentation be updated to show how this can be done with mongoose models?
I have 2 mongo models defined in 2 different files (generated using hpal make model
like so
models/parent.js
'use strict';
const Mongoose = require('mongoose');
module.exports = {
name: 'parent',
schema: new Mongoose.Schema({
name: String,
age: Number
})
};
models/child.js
'use strict';
const Mongoose = require('mongoose');
module.exports = {
name: 'child',
schema: new Mongoose.Schema({
name: String,
age: Number
})
};
What I'm trying to do is define child
as a sub-document array on parent
but it throws an error
'use strict';
const Mongoose = require('mongoose');
const Child = require('./child');
module.exports = {
name: 'parent',
schema: new Mongoose.Schema({
name: String,
age: Number,
children: [Child]
})
};
TypeError: Invalid schema configuration:
Child
is not a valid type at pathname
. See http://bit.ly/mongoose-schematypes for a list of valid schema types.
Pretty sure something needs to be different in the require
statement but not quite sure what it is.
Running on a host of 0.0.0.0
is not a safe default because it could inadvertently expose the app over the network. It's also not suggested to run nodejs without a reverse proxy or similar in front of it. Second, our debug
defaults are redundant (implementation
and internal
tags both always come with an error
tag) and introduce the NODE_ENV
value 'development'
which is not necessary or particularly 12 factor.
Can anyone suggest the better approach to integrate mongoose with hapipal?
i am new in hapi and i really like your boilerplate api but i don't know how can i add plugin
for example i want to add hapi-io plugin for socket and i should put this lines
server.register({
register: require('hapi-io'),
options: {
...
}
});
exports.register = function(server, options, next) {
var io = server.plugins['hapi-io'].io;
};
where should i put them
This can go: https://github.com/devinivy/boilerplate-api/blob/master/server.js#L7-L9
The code is necessarily ugly, and since hapi v8 this already lives on connection.info.uri
.
Hi again! Was your intention for the migrations
directory to live under lib/
?
It just aint necessary!
It appears that swagger UI makes requests not to the current host but instead server.info.host
, which can cause CORS issues. This is most typically seen when running the server at 0.0.0.0
but browser swagger UI on localhost
.
And write a test ensuring that the server ships with x, y, z, and the plugin in lib/. Use latest code and lab.
At least browserify and postcss-cli could use updates in the "templated site" and "fancy templated site" flavors.
And ensure that the plugin is configured solely thru plugin options. This probably means moving bassmaster (among others?) out of the plugin and into the server.
heyo!
now that h17 is out, i was thinking about starting from the boilerplate and re-structuring my application a bit using this boilerplate. any thoughts on h17 compatibility?
cheers,
james
Additionally utilize Schwifty.migrationsStubPath
in the knex config. If you're interested in working on this, branch and make a PR to flavor-objection
.
Not sure if this subproject is the best place for this (maybe it'd be hpal
; please let me know), but right now, the aforementioned concepts are missing and that represents a big problem from the separation of concerns PoV.
Right now, what's the best way to create a view-model
(say, a REST resource/DTO that is different from the Schwifty model
and has different Joi validations, etc.?
What about a translation layer responsible for converting between view-model
and model
?
What about the logic inside the handler of a route
? (IMHO, it'd be useful to have a controller
abstraction for just that, but maybe the expectation is that we'll use a Schmervice service
for it and also for adapter/mapper
implementations if we want to separate things?)
I know things are usually kept simpler in Node/Hapi projects when compared to, let's say, a Java project, but I can't see a proper separation of concerns without at least the inclusion of the view-model
concept.
I want to use mongodb with hapipal,Can you please advice is there any plugin available for mongodb like knex.
Hi,
I created a project using boilerplate and schwifty. When I try to use server.knex().migrate
in test file, it is looking project/migrations
instead of project/lib/migrations
and I got following error:
ENOENT: no such file or directory, scandir '.....project/migrations
test/01-test.js
const Code = require("code");
const Lab = require("lab");
const Server = require("../server");
const Package = require("../package.json");
const { describe, it, beforeEach, before } = (exports.lab = Lab.script());
const { expect } = Code;
let server;
before(async () => {
server = await Server.deployment();
});
beforeEach(async () => {
const knex = await server.knex();
await knex.migrate.rollback();
await knex.migrate.latest();
await knex.seed.run();
});
describe("Deployment", () => {
it("registers the main plugin.", async () => {
expect(server.registrations[Package.name]).to.exist();
});
});
lib/plugins/schwifty
There is no lib
like it is swallowed:
Produces ENOENT: no such file or directory, scandir '.....project/migrations
module.exports = {
plugins: {
options: {
migrationsDir: `${__dirname}/../migrations`,
},
},
};
Additional notes:
npx knex migrate:rollback
works as expectedThanks
service-x/ ├── lib/ │ ├── routes │ ├── get-student.js │ ├── new-student.js │ ├── server/ service-y/ ├── lib/ ├── server/ service-z/ ├── lib/ ├── server/ gateway-service/ ├── lib/ │ ├── routes │ ├── gw-get-student.js │ ├── gw-new-student.js │ ├── plugins │ ├── service-x.js │ ├── service-y.js │ ├── service-z.js ├── server/
Service-x, y and z are micro services. "gateway-service" act as proxy/gateway service to all other services.
I want to add all the "x/y/z" services as a plugin to "gateway-service". And for that, I created files in "lib/plugins" directory and its registered successfully.
But I am not sure how do I call the "service-x" route handler from "gateway-service" handler. !!!!
Can you please help me on this?
I designed this way, so that initially i will deploy the App as one Monolithic app. If required I can deploy as individual micro service as well. Is this design is correct ?
Per @zemccartney in #62
It's your favorite person again! lol
This may be something that's personal preference, but curious where you store most of your business logic? Are you doing most things in your handlers or do you store logic in your Objection models?
For example, with my other project, the vast majority of my logic lies in my models -- making the handlers very light.
Again, just trying to weed out some best practices. I realize there's many ways to do things, but it's always good to hear from others!
In the readme after completing Getting Started section I continue to Flavors:
hpal new my-project
cd ./my-project
git cherry-pick templated-site
error: refusing to lose untracked file at 'server/manifest.js'
git add -A :/, git commit -m "blabla"
git cherry-pick templated-site
error: after resolving the conflicts, mark the corrected paths
If I have to run git clone
instead of hpal new my-project
then it's not clear from the readme.
Thank you for your work.
When NODE_ENV
is set to 'dev'
, enable server debug mode. We need to settle on which tags to log. Debug will by default be preferred over good logging in this environment.
Hi,
I would like to test a hapipal project that uses Schwifty. I could create simple unit tests for the Schwifty models without actually requiring the server at all, but when I would like to test my routes I don't know how to get
Example router:
'use strict'
const Joi = require('joi')
const handler = async function (request, h) {
// console.log('realm2', request.route.realm)
console.log('models', request.models())
const { Championship } = request.models()
const rounds = await Championship.query()
.eagerAlgorithm(Championship.JoinEagerAlgorithm)
.eager('[matches(orderByCode).[guest_team, home_team], children, main]')
.findById(request.params.championshipId)
return rounds
}
module.exports = {
method: 'GET',
path: '/championships/{championshipId}',
config: {
auth: false,
validate: {
params: {
championshipId: Joi.number()
}
}
},
handler
}
and the accompanying test (as I imagine it) would start somehow like:
'use strict'
const Server = require('../../../server')
// Load modules
const Championship = require('../../models/Championship')
const config = require('../championship-get')
// Test shortcuts
describe('Championship get', () => {
let server
beforeAll(async () => {
server = await Server.deployment(false) // I prefer not to listen in a test
await server.knex().migrate.latest('../lib/migrations') // migrations should run as per manifest, but they don't, and setting the path here is ignored for some reason
server.route(config)
})
beforeEach(async () => {
await Championship.query(server.knex()).insert({
name: 'WSB 2018'
})
})
test('calls its handler', async () => {
const res = await server.inject({
method: 'GET',
url: '/championships/1',
headers: {}
})
expect(res.statusCode).toEqual(200)
})
})
The above fails as request.models()
is empty.
I've figured out that models are to be parsed at the onPreStart event, but I would not start a server when I'm testing. Is there a way to still access models in requests?
Hi again,
When exactly would you use server/plugins
vs lib/plugins
?
Thanks!
I just boostrapped a project using the CLI and used the deployment
flavor. I noticed the flavor is not using the @hapi
scoped package. I'd be happy to update it but I wondered what is the preferred workflow for it. I noticed there is a flavor-deployment
branch and also the tag we cherry-pick. My guess is that you make the change on the branch, commit and after that you update the deployment
tag (if I have the right to do it) on the HEAD of that branch, is that correct?
Thanks 👍
The templated site and fancy templated site flavors use uglify to create production JS builds. Currently this works because handlebars depends on uglify, but we should also depend on it explicitly.
Update dotenv to v5 in the vanilla boilerplate. Will also require special updates to the "deployment" flavor, I would guess. Also research https://github.com/sholladay/envy as a potential way forward.
do you have a good system for using Knex for integration testing? Specifically curious how you go about resetting the database before every test. I've tried a few things but running into gotchas!
Note: I felt like this was relevant to the boilerplate, but if you don't, feel free to close 😄
Modules in the hapijs org now are published under the @hapi/x scope. References to these dependencies need to be updated. This would also be a good time to ensure deps are up to date. I believe the only one needing updating will be joi. Also need to sweep flavors.
I'm new to node and I'm checking out your repo...thanks!! I have everything up and running but I can't see to get testing going.
I'm assuming that since your are exporting the manifest in server.js
that you would create the server via Glue in each of your test files. Whenever I do this it never calls the callback passed to Glue.compose
Am I setting this up right?
// test/test.js
var Glue = require('glue');
var Path = require('path');
var manifest = require("../server.js");
Glue.compose(manifest, { relativeTo: Path.join(__dirname, '../node_modules') }, function (err, server) {
// We never get here..
if (err) {
throw err;
}
console.log('begin tests');
});
Test Output:
0 tests complete
Test duration: 0 ms
No global variable leaks detected
I'm going to play with adding eslint to the chalice-api, and it seems like it might be worth adding in here too, thoughts, @devinivy ? If I get it working, I'd be happy to put together a PR.
Mostly need to make sure we construct paths correctly. I know this is an issue right now.
Want to a CONTRIBUTING.md
added similar to hapi's:
Build the main boilerplate plugin using haute-couture. Also include .gitkeep
s for directories whose corresponding features we'd like to encourage, like methods/
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.