Created
August 10, 2017 16:48
-
-
Save doron2402/307cd04853010e7bb9d4f48b1740d71b to your computer and use it in GitHub Desktop.
Hapi.js with hapi-plugin-pg plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// index.js | |
‘ | |
use strict’; | |
const Hapi = require(‘hapi’); | |
const Joi = require(‘joi’); | |
const server = new Hapi.Server(); | |
server.connection({ | |
port: 3000, | |
host: ‘localhost’ | |
}); | |
server.register({ | |
register: require(‘hapi - plugin - pg’), | |
options: { | |
connectionString: ‘postgres: //USERNAME:PASSWORD@localhost:5432/DATBASE_NAME’ | |
} | |
}, (err) => { | |
if (err) { | |
throw err; | |
} | |
}); | |
server.route({ | |
method: ‘GET’, | |
path: ‘ /username/ { | |
name | |
}’, | |
handler: function (request, reply) { | |
const username = request.params.name; | |
request.pg.client.query(“SELECT * FROM users where username = $1”, [username], (err, result) => { | |
if (err) { | |
return reply(err).code(500); | |
} | |
if (!result || !result.rows || result.rows.length === 0) { | |
return reply({ | |
body: ‘Not Found’ | |
}).code(404); | |
} | |
return reply(result.rows); | |
}); | |
}, | |
config: { | |
validate: { | |
params: Joi.object({ | |
name: Joi.string().alphanum().required() | |
}) | |
} | |
} | |
}); | |
server.route({ | |
method: ‘GET’, | |
path: ‘ /id/ { | |
id | |
}’, | |
handler: function (request, reply) { | |
const id = request.params.id; | |
request.pg.client.query(“SELECT * FROM users where id = $1”, [id], (err, result) => { | |
if (err) { | |
return reply(err).code(500); | |
} | |
if (!result || !result.rows || result.rows.length === 0) { | |
return reply({ | |
body: ‘Not Found’ | |
}).code(404); | |
} | |
return reply(result.rows); | |
}); | |
}, | |
config: { | |
validate: { | |
params: Joi.object({ | |
id: Joi.number().integer().required() | |
}) | |
} | |
} | |
}); | |
server.start((err) => { | |
if (err) { | |
throw err; | |
} | |
console.log(`Server running at: ${server.info.uri}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment