Tech/NodeJs
-
express 와 singleton 패턴을 사용한 api server 구현Tech/NodeJs 2020. 1. 11. 13:05
MSA 와 무중단 배포 특성에 맞는 api server 를 구축 해보도록한다. //server.js 'use strict' const express = require('express') const http = require('http') const cookieParser = require('cookie-parser') //http.Server 를 통해 확장하여 싱글톤 패턴으로 만들도록 한다. //서버가 이중으로 생성되는것을 막기 위해 싱글톤으로 구현하도록 한다. //MSA 환경을 고려했을때 일관성있게 분산된 서버들의 상태를 관리하기 위함이다. //즉 생성자 내부에서 express 생성을 한번만 생성하도록 싱글톤 패턴을 적용하는 기법이다. class ApiServer extends http.Server {..
-
static method factory patternTech/NodeJs 2020. 1. 10. 21:29
'use statict' /** * static method factory pattern * 기존 construct 를 통한 생성이 아닌 static method 로 객체 생성 */ class DatabaseManager { constructor(settings) {} //초기화를 생성자가 아닌 static 으로 생성하도록 한다. static async build(settings) { const config = await this.init(settings) return new DatabaseManager(config) } query() {} async init() {} // 최초 1회 실행 async newMember() {} async deleteMember() {} } //usage const man..
-
fileTech/NodeJs 2020. 1. 10. 21:28
const fs = require('fs') //비구조화 방식으로 필요한것만 받음 const {promisify} = require('util') //콜백함수로 사용 const read = promisify(fs.readFile) const write = promisify(fs.writeFile) const writeAndRead = async (data = '') => { try{ await write('text.txt',data) return (await read('text.txt')) }catch(e){ console.error(e) } } writeAndread('some contents')
-
classTech/NodeJs 2020. 1. 10. 21:27
class cacheManage{ constructor(){ this.config = [] } addConfig(obj={}){ this.config.push(obj) } getConfig() { return this.config } } const CacheManage = new cacheManage() CacheManage.addConfig({ port: 8080 }) const config = CacheManage.getConfig() module.exports = cacheManage
-
arrow functionTech/NodeJs 2020. 1. 10. 21:26
일반적인 함수를 arrow 로 변환 하기 const add = function add(var1,var2) { return var1+var2 } const add = (var1,var2) => var1 + var2 const add = (var1,var2) => console.log(var1 + var2) API.prototype.get = function(resource) { var self = this; return new Promise(function(resolve, reject){ http.get(self.uri + resource,function(data) { resolve(data); }); }); }; API.prototype.get = (resource)=>{ new Promise((reso..
-
error handlingTech/NodeJs 2020. 1. 10. 21:26
const CustomError = (message) => { //객체로 오류 상태를 던지도록 한다 this.message = message this.type = 'NotImageFileException' } try { const imgTypes = ['.jpg','.png'] const fileName = 'node.doc' const isImageFile = imgTypes.find(ext => fileName.endWith(item)) if(!isImageFile){ throw new CustomError('this is not a image file') //throw new 'this is not a image file' } }catch(e){ console.log(e) }