Commit e1e92ddc authored by Trai Nguyen's avatar Trai Nguyen

add swagger

parent 01f3d31c
...@@ -80,7 +80,7 @@ gulp.task(GENERATE_DOC, gulp.series(CLEAN_DOC, function () { ...@@ -80,7 +80,7 @@ gulp.task(GENERATE_DOC, gulp.series(CLEAN_DOC, function () {
return gulp.src(TS_SRC_GLOB) return gulp.src(TS_SRC_GLOB)
.pipe(typedoc({ .pipe(typedoc({
out: "docs", out: "docs",
target: "es5", target: "es6",
name: "Express + Sequelize", name: "Express + Sequelize",
module: "commonjs", module: "commonjs",
readme: "readme.md", readme: "readme.md",
......
{ {
"name": "typescript-express-sequelize", "name": "typescript-express-postgresql-sequelize",
"version": "2.1.0", "version": "1.0.0",
"description": "Sample project with Express + Sequelize + Typescript", "description": "A sample project with Express + Sequelize + Typescript + Postgresql",
"homepage": "https://github.com/maximegris/typescript-express-sequelize", "homepage": "",
"author": { "author": {
"name": "Maxime GRIS", "name": "Author",
"email": "maxime.gris@gmail.com" "email": "email@yourdomain.com"
}, },
"main": "build/src/server.js", "main": "build/src/server.js",
"keywords": [ "keywords": [
...@@ -34,15 +34,17 @@ ...@@ -34,15 +34,17 @@
"dependencies": { "dependencies": {
"body-parser": "1.19.0", "body-parser": "1.19.0",
"cors": "2.8.5", "cors": "2.8.5",
"cross-env": "7.0.0", "cross-env": "^7.0.0",
"express": "4.17.1", "express": "4.17.1",
"express-boom": "3.0.0", "express-boom": "3.0.0",
"kafka-node": "^5.0.0",
"express-validator": "^6.9.2", "express-validator": "^6.9.2",
"kafka-node": "^5.0.0",
"morgan": "1.9.1", "morgan": "1.9.1",
"pg": "^8.5.1", "pg": "^8.5.1",
"pg-hstore": "^2.3.3", "pg-hstore": "^2.3.3",
"sequelize": "^6.5.0", "sequelize": "^6.5.0",
"swagger-jsdoc": "^6.0.7",
"swagger-ui-express": "^4.1.4",
"uuid": "3.4.0", "uuid": "3.4.0",
"winston": "3.2.1" "winston": "3.2.1"
}, },
......
{
"development": {
"username": "postgres",
"password": "meu@sds12@!#gh",
"database": "chinguyen_nodejs-practice",
"host": "27.74.255.96",
"port": 5430,
"dialect": "postgres"
}
}
\ No newline at end of file
import * as LanguagesDao from './languages' import * as LanguagesDao from './languages'
import * as AppUserDao from './appusers' import * as AppUserDao from './appusers'
import * as StudentDao from './students' import * as StudentDao from './students'
import * as ConsumerDao from '../kafka/consumerMessage' // For kafka only
import * as ProducerDao from '../kafka/messageProducer' // import * as ConsumerDao from '../kafka/consumerMessage'
// import * as ProducerDao from '../kafka/messageProducer'
export { LanguagesDao } export { LanguagesDao }
export { AppUserDao } export { AppUserDao }
export { StudentDao } export { StudentDao }
export { ConsumerDao } // For kafka only
export { ProducerDao } // export { ConsumerDao }
// export { ProducerDao }
import * as uuid from 'uuid' import * as uuid from 'uuid'
import { Students } from './../sqlz/models/students' import { Students } from './../sqlz/models/students'
import { where, Op } from 'sequelize/types'; import { where, Op } from 'sequelize/types'
import { Request, Response } from 'express' import { Request, Response } from 'express'
export function create(students: any): Promise<any> { export function create(students: any): Promise<any> {
return Students.create({ return Students.create({
id: uuid.v1(), id: uuid.v1(),
code: students.code, code: students.code,
firstname: students.firstname, firstname: students.firstname,
lastname: students.lastname, lastname: students.lastname,
email: students.email, email: students.email,
sdt: students.sdt sdt: students.sdt
})
})
} }
export function findAll(): Promise<any> { export function findAll(): Promise<any> {
return Students.findAll() return Students.findAll()
} }
export function findStudentPagination (page:any, pagesize:any): Promise<any>{ export function findStudentPagination(page: any, pagesize: any): Promise<any> {
return Students.findAndCountAll({ return Students.findAndCountAll({
offset: (page - 1 ) * pagesize, offset: (page - 1) * pagesize,
limit: pagesize limit: pagesize
//offset: 1, //offset: 1,
//limit: 2 //limit: 2
}) })
}
}
export function deleteUser(code: any): Promise<any> { export function deleteUser(code: any): Promise<any> {
return Students.destroy({ return Students.destroy({
where:{code} where: { code }
}) })
} }
export function updateUser(code: any, students: any): Promise<any> { export function updateUser(code: any, students: any): Promise<any> {
return Students.findOne({ return Students.findOne({
where: {code} where: { code }
}).then(function(student) { }).then(function(student) {
if (student) { if (student) {
student.update({ student.update({
firstname: students.firstname, firstname: students.firstname,
lastname: students.lastname, lastname: students.lastname,
email: students.email, email: students.email,
sdt: students.sdt sdt: students.sdt
}) })
} }
}) })
} }
import * as LanguageController from './languages/_index' import * as LanguageController from './languages/_index'
import * as AppUserController from './appusers/_index' import * as AppUserController from './appusers/_index'
import * as StudentsController from './students/_index' import * as StudentsController from './students/_index'
import * as ConsumerController from './consumer/_index' // For kafka only
import * as ProducerController from './producer/_index' // import * as ConsumerController from './consumer/_index'
// import * as ProducerController from './producer/_index'
export { LanguageController, AppUserController, StudentsController, ConsumerController, ProducerController } export { LanguageController, AppUserController, StudentsController }
import * as ConsumerGet from './consumerMessage.get'
export { ConsumerGet }
import { Request, Response } from 'express'
import { ConsumerDao } from '../../dao/_index'
export function getMessage(req: Request, res: Response) {
return ConsumerDao.receiveMessage();
}
import * as ProducerPost from './producerMessage.post'
export { ProducerPost }
import { ProducerDao } from '../../dao/_index'
import { Request, Response } from 'express'
export function producer(req: Request, res: Response) {
return ProducerDao.produceMessage();
}
File added
import * as kafka from 'kafka-node';
//import {getConsumer} from './message'
export function receiveMessage(): any {
const _that = this;
let topicName = 'message-chinguyen';
let produceTopic = topicName;
let kafkaConsumer = kafka.Consumer;
let Client = kafka.KafkaClient;
let client = new Client({ kafkaHost: 'localhost:9092' })
let consumer = new kafkaConsumer(client, [{ topic: produceTopic }], { autoCommit: false, fetchMaxWaitMs: 1000, fetchMaxBytes: 1024 * 1024 })
consumer.on('message', function(message) {
console.log(message);
});
consumer.on('error', function(err) {
console.log('error', err);
});
}
import * as kafka from 'kafka-node';
//import {} from 'optimist'
let clientOpts = {
kafkaHost: 'localhost:9092',
//sasl: configuration.kafkaClient.sasl,
connectTimeout: 10000,
maxAsyncRequests: 10,
requestTimeout: 30000
};
// Create Producer
let MessageProducer = kafka.Producer,
aaClient = new kafka.KafkaClient(clientOpts),
messageProducer = new MessageProducer(aaClient, { requireAcks: 1 })
messageProducer.on('ready', function() {
setMessageProducer(messageProducer);
});
export function getMessageProducer(): kafka.Producer {
return messageProducer;
}
export function setMessageProducer(producerObj: kafka.Producer): void {
messageProducer = producerObj;
}
///
import { Producer } from 'kafka-node'
import { getMessageProducer } from './message'
export function produceMessage() {
const _that = this;
let producer = getMessageProducer();
let topicName = 'message-chinguyen';
let produceTopic = topicName;
let payloads: {
topic: any;
messages: any;
key: any;
attributes: any;
timestamp: any;
}[] = [];
let curTimestamp = Date.now();
payloads.push({ topic: produceTopic, messages: 'hahahahaha', key: 1, attributes: 'haha', timestamp: curTimestamp });
if (payloads.length > 0) {
producer.send(payloads, function(err, data) {
if (err) {
console.log("error");
}
else {
console.log("success");
}
});
}
}
...@@ -2,7 +2,16 @@ import { Express } from 'express' ...@@ -2,7 +2,16 @@ import { Express } from 'express'
import { AppUserController } from '../endpoints/_index' import { AppUserController } from '../endpoints/_index'
export function routes(app: Express) { export function routes(app: Express) {
app.get('/api/appUsers', AppUserController.AppUserGet.list) /**
app.post('/api/appUsers', AppUserController.AppUserPost.getValidationRules("CreateUser"), AppUserController.AppUserPost.createUser) * @swagger
app.post('/api/appUsers/login', AppUserController.AppUserPost.getValidationRules("Login"), AppUserController.AppUserPost.login) * /api/users:
* get:
* description: Get all users
* responses:
* '200':
* description: A successful response
*/
app.get('/api/users', AppUserController.AppUserGet.list)
app.post('/api/user', AppUserController.AppUserPost.getValidationRules('CreateUser'), AppUserController.AppUserPost.createUser)
app.post('/api/user/login', AppUserController.AppUserPost.getValidationRules('Login'), AppUserController.AppUserPost.login)
} }
import { Express } from 'express'
import { ConsumerController, ProducerController } from '../endpoints/_index'
export function routes(app: Express) {
app.post('/api/producerMessage', ProducerController.ProducerPost.producer)
app.get('/api/consumerMessage', ConsumerController.ConsumerGet.getMessage)
}
...@@ -6,6 +6,9 @@ import * as cors from 'cors' ...@@ -6,6 +6,9 @@ import * as cors from 'cors'
import { json, urlencoded } from 'body-parser' import { json, urlencoded } from 'body-parser'
import { Express } from 'express' import { Express } from 'express'
import * as routes from './routes/_index' import * as routes from './routes/_index'
import * as specs from './swagger'
import * as swaggerUi from 'swagger-ui-express'
const PORT: number = 3000 const PORT: number = 3000
...@@ -14,22 +17,23 @@ const PORT: number = 3000 ...@@ -14,22 +17,23 @@ const PORT: number = 3000
* Can be used for basic configurations, for instance starting up the server or registering middleware. * Can be used for basic configurations, for instance starting up the server or registering middleware.
*/ */
export class Server { export class Server {
private app: Express private app: Express
constructor() { constructor() {
this.app = express() this.app = express()
// Express middleware // Express middleware
this.app.use(cors({ this.app.use(cors({ optionsSuccessStatus: 200 }))
optionsSuccessStatus: 200 this.app.use(urlencoded({ extended: true }))
}))
this.app.use(urlencoded({
extended: true
}))
this.app.use(json()) this.app.use(json())
this.app.use(boom()) this.app.use(boom())
this.app.use(morgan('combined')) this.app.use(morgan('combined'))
if (process.env["EnvironmentName"] == "development") {
this.app.use('/swagger', swaggerUi.serve, swaggerUi.setup(specs.default));
}
this.app.listen(PORT, () => { this.app.listen(PORT, () => {
winston.log('info', '--> Server successfully started at port %d', PORT) winston.log('info', '--> Server successfully started at port %d', PORT)
}) })
......
import * as swaggerJsdoc from 'swagger-jsdoc'
const options = {
apis: ['**/*.ts'],
explorer: true,
swaggerDefinition: {
info: {
swagger: '2.0',
title: "Sample project APIs doc",
description: "Your project description here",
contact: {
name: "Author name"
},
version: '1.0.0'
}
}
};
const specs = swaggerJsdoc(options);
export default specs;
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
"module": "commonjs", "module": "commonjs",
"declaration": false, "declaration": false,
"noImplicitAny": false, "noImplicitAny": false,
"resolveJsonModule": true,
"skipLibCheck": true,
"removeComments": true, "removeComments": true,
"noLib": false, "noLib": false,
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment