https://nodejs.org/ko/
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}/`);
});
https://nodejs.org/dist/latest-v6.x/docs/api/synopsis.html
{
"scripts": {
"start": "node app.js"
}
}
package.json
function foo() {
if (false) {
var a = 1;
}
console.log(a);
}
foo(); // undefined
function foo() {
var a;
if (false) {
a = 1;
}
console.log(a);
}
foo(); // undefined
function foo() {
if (false) {
let a = 1;
}
console.log(a);
}
// ReferenceError:
// a is not defined
foo();
function foo() {
if (false) {
let a;
a = 1;
}
console.log(a);
}
// ReferenceError:
// a is not defined
foo();
const a = 1;
// TypeError:
// Assignment to constant variable.
a = 2;
// SyntaxError:
// Missing initializer in const declaration
const b;
var foo = function(param) {
return true;
}
const foo = (param) => {
return true;
}
const foo = param => true;
foo.js
bar.js
require('foo')
function sum(a, b) {
return a + b;
}
// sum()을 외부 노출 -> 모듈로 만듬
module.exports = sum;
const sum = require('./sum.js');
console.log(sum(1, 2)); // 3
HTTP
client
Server
CRUD | Method |
---|---|
Create | POST |
Read | GET |
Update | PUT |
Delete | DELETE |
Status Code
Content-Type: text/json
Content-Length: 13
...
배열이나 객체
[{
id: 1,
name: 'Alice'
}, {
id: 2,
name: 'Bek'
}, {
id: 3,
name: 'Chris'
}]
상태 코드 | 의미 |
---|---|
200 | Success |
201 | Created |
204 | No Content |
상태 코드 | 의미 |
---|---|
400 | Bad Request |
401 | Unauthorized |
404 | Not Found |
409 | Conflict |
상태 코드 | 의미 |
---|---|
500 | Internel Error |
let users = [
{
id: 1,
name: 'alice'
},
{
id: 2,
name: 'bek'
},
{
id: 3,
name: 'chris'
}
]
app.get('/users', (req, res) => {
// 여기에 라우팅 로직을 작성하면 됩니다.
});
app.get('/users/1', (req, res) => /* ... */);
app.get('/users/2', (req, res) => /* ... */);
app.get('/users/:id', (req, res) => {
console.log(req.params.id);
});
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
});
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
if (!id) {
return res.status(400)
.json({error: 'Incorrect id'});
}
});
function User(_name) {
this.name = _name;
}
User.prototype.greeting = function() {
console.log('Hello! ');
return this;
};
User.prototype.introduce = function() {
console.log(`I am ${this.name}`);
return this;
};
var chris = new User('chris');
chris.greeting().introduce();
let user = users.filter(user => {
return user.id === id;
});
console.log(user); // [{id: 1, name: 'alice'}]
app.get('/users/:id', (req, res) => {
let user = users.filter(user => user.id === id)[0]
if (!user) {
return res.status(404)
.json({error: 'Unknown user'});
}
});
app.get('/users/:id', (req, res) => {
// return res.status(200).json(user);
// or
return res.json(user);
});
const userIdx = users.findIndex(user => {
return user.id === id;
});
if (userIdx === -1) {
return res.status(404)
.json({error: 'Unknown user'});
}
if (!name.length) {
return res.status(400)
.json({error: 'Incorrenct name'});
}
const newUser = {
id: id,
name: name
};
users.push(newUser);
const router = express.Router();
// Database Mockup
let users = [/* ... */];
router.get('/:id', (req, res) => {/* ... */});
router.get('/', (req, res) => {/* ... */});
router.delete('/:id', (req, res) => {/* ... */});
router.post('/:id', (req, res) => {/* ... */});
module.exports = router;
// Database Mockup
let users = [/* ... */];
exports.index = (req, res) => {/* ... */});
exports.get = (req, res) => {/* ... */});
exports.destroy = (req, res) => {/* ... */});
exports.create = (req, res) => {/* ... */});
const router = express.Router();
const ctrl = require('./user.controller');
router.get('/:id', ctrl.show);
router.get('/', ctrl.index);
router.delete('/:id', ctrl.destroy);
router.post('/:id', ctrl.create);
module.exports = router;
const assert = require('assert');
describe('test suite', () => {
it('true is true', (done) => {
assert.equal(true, true);
});
});
{
"scripts": {
"test": "node_modules/.bin/mocha api/user/user.spec.js"
}
}
const should = require('should');
describe('test suite', () => {
it('true is true', (done) => {
(true).should.be.euqal(true);
});
});
const request = require('supertest');
const app = require('../../app');
describe('GET /users', () => {
it('should return 200 status code', (done) => {
request(app)
.get('/users')
.expect(200)
.end((err, res) => {
if (err) throw err;
console.log(res.body);
// [{id: 1, name: 'Alice'} ... ]
done();
})
});
});
res.body.should.be.an.instanceof(Array)
.and.have.length(3);
res.body.map(user => {
user.should.have.properties('id', 'name');
user.id.should.be.a.Number();
user.name.should.be.a.String();
});
Table1
Table2
Object1
{
id: 1
name: 1
}
Object2
{
id: 1
name: 1
}
Object3
{
id: 1
name: 1
}
Table3
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node_api_codelab', 'root', 'root')
const User = sequelize.define('user', {
name: Sequelize.STRING
});
module.exports = {
sequelize: sequelize,
User: User
}
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
require('./models').sequelize.sync({force: true})
.then(() => {
console.log('Databases sync');
});
});
exports.create = (req, res) => {
const name = req.body.name || '';
if (!name.length) {
return res.status(400).json({error: 'Incorrenct name'});
}
models.User.create({
name: name
}).then((user) => res.status(201).json(user))
};
exports.index = (req, res) => {
models.User.findAll()
.then(users => res.json(users));
};
exports.show = (req, res) => {
models.User.findOne({
where: {
id: id
}
}).then(user => {
if (!user) {
return res.status(404).json({error: 'No User'});
}
return res.json(user);
});
};
exports.destroy = (req, res) => {
models.User.destroy({
where: {
id: id
}
}).then(() => res.status(204).send());
};
const environments = {
development: {
mysql: {
username: 'root',
password: 'root',
database: 'node_api_codelab_dev'
}
},
test: {
mysql: {
username: 'root',
password: 'root',
database: 'node_api_codelab_test'
}
},
production: {
}
}
const nodeEnv = process.env.NODE_ENV || 'development';
module.exports = environments[nodeEnv];
const Sequelize = require('sequelize');
const config = require('./config/environment');
const sequelize = new Sequelize(
config.mysql.database,
config.mysql.username,
config.mysql.password);
const models = require('../models');
module.exports = () => {
return models.sequelize.sync({force: true})
}
const app = require('../app');
const syncDatabase = require('./sync-database');
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
syncDatabase().then(() => {
console.log('Database sync');
});
});
{
"scripts": {
"start": "node bin/www"
}
}
before('sync database', (done) => {
syncDatabase().then(() => done());
});
before('insert seed user data', (done) => {
models.User.bulkCreate(users).then(() => done());
})
after('delete seed user data', (done) => {
models.User.destroy({
where: {
name: {
in: users.map(user => user.name)
}
}
});
});
{
"scripts": {
"test": "NODE_ENV=test node_modules/.bin/mocha api/user/user.spec.js"
}
}
Hints