Skip to content
This repository has been archived by the owner on Jun 4, 2019. It is now read-only.

Commit

Permalink
Build the RESTful API for Articles.
Browse files Browse the repository at this point in the history
  • Loading branch information
RainEggplant committed Aug 15, 2018
1 parent 7f9aceb commit fa5ce47
Show file tree
Hide file tree
Showing 11 changed files with 516 additions and 282 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,6 @@ typings/

# next.js build output
.next

# VSCode file
.vscode/*
40 changes: 29 additions & 11 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
var createError = require("http-errors");
var express = require("express");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const createError = require("http-errors");
const express = require("express");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const mongoose = require("mongoose");
const autoIncrement = require("mongoose-auto-increment");

/**
* Open database.
*/
mongoose.connect(
"mongodb://localhost:27017/sast-app",
{ useNewUrlParser: true }
);
const db = mongoose.connection;
autoIncrement.initialize(db);
db.on("error", console.error.bind(console, "Database connection error: "));
db.once("open", () => {
console.log("Database connected.");
});

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const articlesRouter = require("./routes/articles");

var app = express();
const app = express();

app.use(logger("dev"));
app.use(express.json());
Expand All @@ -15,19 +32,20 @@ app.use(cookieParser());

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/articles", articlesRouter);

// catch 404 and forward to error handler
// catch 404 and forward to error handler.
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
// error handler.
app.use(function(err, req, res, next) {
// set locals, only providing error in development
// set locals, only providing error in development.
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
// render the error page.
res.status(err.status || 500);
res.render("error");
});
Expand Down
42 changes: 19 additions & 23 deletions bin/www
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,37 @@
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('sast-app-backend:server');
var http = require('http');
const app = require("../app");
const debug = require("debug")("sast-app-backend:server");
const http = require("http");

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);
const server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
server.on("error", onError);
server.on("listening", onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);
const port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
Expand All @@ -54,22 +54,20 @@ function normalizePort(val) {
*/

function onError(error) {
if (error.syscall !== 'listen') {
if (error.syscall !== "listen") {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

// handle specific listen errors with friendly messages
// handle specific listen errors with friendly messages.
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
Expand All @@ -82,9 +80,7 @@ function onError(error) {
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
}
4 changes: 2 additions & 2 deletions data/setup.bat
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
rem Setup local database for debug on Windows
rem Setup local database for debug on Windows.
cd ./data
"C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" --dbpath ./db
"D:\Program Files\MongoDB\bin\mongod.exe" --dbpath ./db
22 changes: 22 additions & 0 deletions helpers/existenceVerifier.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* 判断特定对象是否已存在。
* @param {Object} ModelType 对象类型
* @param {JSON} query 查询条件
* @returns {Object | Boolean} 存在则返回对象,不存在返回 false
*/
// TODO: return Object itself.
const existenceVerifier = (ModelType, query) => {
return new Promise(resolve =>
ModelType.findOne(query, (err, object) => {
if (err) {
resolve(null);
} else if (object) {
resolve(object);
} else {
resolve(false);
}
})
);
};

module.exports = existenceVerifier;
27 changes: 26 additions & 1 deletion models/article.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,39 @@
/**
文章示例
Notice
{
title: 'Test',
content: 'Hello, world!',
attachments: ['file1.docx', 'file2.docx'],
tags: ['Tutorials']
createdAt: '2018-05-16T17:01:42.346Z',
createdBy: '张三',
updatedAt: '2018-05-16T17:01:42.346Z',
updatedBy: '张三'
}
*/

const mongoose = require("mongoose");
const autoIncrement = require("mongoose-auto-increment");

const articleSchema = new mongoose.Schema(
{
title: String
title: String,
content: String,
attachments: [String],
tags: [String],
createdAt: { type: Date, default: Date.now },
createdBy: String,
updatedAt: { type: Date, default: Date.now },
updatedBy: String
},
{
collection: "articles"
}
);

articleSchema.plugin(autoIncrement.plugin, "Article");
const Article = mongoose.model("Article", articleSchema);

module.exports = Article;
Loading

0 comments on commit fa5ce47

Please sign in to comment.