Ejemplo de un simple servidor web con Nodejs:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Diferencias entre callbacks, promesas, generadores, async/await
// callback
const authenticateUser = (ctx, next) => {
User.findOne({
name: ctx.req.user.dataValues.name
}, (err, user) => {
if (err) return next(err)
if (user) {
return user.veryfyPassword(ctx.request.body.password, (err, isPasswordMatch) => {
if (err) return next(err)
if (isPasswordMatch) {
return issueToken(user._id, (err, token) => {
if (err) return next(err)
ctx.body = {
status: 200,
token: token,
}
})
}
ctx.body = {
status: 401,
}
})
}
ctx.body = {
status: 401,
}
})
}
// Promesa
const authenticateUser = (ctx, next) => {
User.findOne({
name: ctx.req.user.dataValues.name
})
.bind({})
.then(user => {
this.user = user
if (user)
return user.veryfyPassword(ctx.request.body.password)
return Promise.resolve(false)
})
.then(isPasswordMatch => {
if (isPasswordMatch)
return issueToken(this.user._id)
return Promise.resolve(null)
})
.then(token => {
if (token)
return ctx.body = {
status: 200,
token: token,
}
ctx.body = {
status: 401,
}
})
.catch(err => {
next(err)
})
}
//generadores
const authenticateUser = (ctx, next) => {
Promise.coroutine(function* () {
try {
const user = yield User.findOne({ name: ctx.req.user.dataValues.name })
const isPasswordMatch = (user) ? yield user.veryfyPassword(ctx.request.body.password) : false
const token = (isPasswordMatch) ? yield issueToken(user._id) : false
if (token) {
ctx.body = {
status: 200,
token: token,
}
}
ctx.body = {
status: 401,
}
} catch (err) {
next(err)
}
})()
}
// async/await
const authenticateUser = async (ctx, next) => {
try {
const user = await User.findOne({ name: ctx.req.user.dataValues.name })
const isPasswordMatch = (user) ? await user.veryfyPassword(ctx.request.body.password) : false
const token = (isPasswordMatch) ? await issueToken(user._id) : false
if (token) {
ctx.body = {
status: 200,
token: token,
}
return
}
ctx.body = {
status: 401,
}
} catch (err) {
next(err)
}
}