New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

etm

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

etm

a nodejs server with express and typescript

  • 2.0.7
  • unpublished
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

ETM NodeJs 服务器框架

ETM使用的是typescript和express的组合, 同时封装了MySQL,已方便直接使用, 只需要进行简单的配置即可创建好一个nodejs web服务器。

如何安装?

npm install ets --save

ETM提供了哪些模块?

  • ETM (服务器主要模块)

  • Config (服务器配置)

  • Route (路由)

  • HttpsCert (https协议证书类)

  • Protocol (网络协议)

  • ViewEngine (视图引擎)

  • StyleSheet (样式表)

  • MySQL (MySQL数据库操作)

  • MySQLConfig (MySQL数据库配置)

  • WebSocketHandler (Websocket消息处理)

如何创建一个服务器?

创建服务器需要以下三部

  • new一个ETM对象,传入服务器选项
  • 调用addRoute方法添加路由
  • 调用createServer方法创建服务器

示例如下

//初始化服务器
let server = new ETM(config);
//添加路由
server.addRoute('', Index);
//创建服务器
server.createServer();

服务器选项有哪些?

  • 端口号(默认是3000,使用setPort方法更改端口号)
  • 服务器协议(默认是Protocol.HTTP,使用setProtocol方法更改协议类型,如果是https则必须传证书参数)
  • https证书(如果服务器协议为Protocol.HTTPS,则必须传入证书)
  • 跨域访问(默认是false,使用crossDomain方法可以设置是否跨域)
  • 文件上传缓存目录(默认/tmp/ets,使用setCachePath方法设置)
  • 网页静态资源目录(必须设置,使用setStaticPath方法设置)
  • 视图目录(必须设置,使用setView方法设置)
  • 视图引擎(默认是ViewEngine.hbs,使用setView方法可以更改)
  • 样式表(默认是StyleSheet.less,使用setView方法可以更改)

如何创建https服务器?

创建https服务器需要提供证书。

将证书放到任意目录(一般在项目中新建一个cert目录放置https证书)。

使用new HttpsCert(.key文件的绝对路径,.pem文件的绝对路径) 创建一个证书对象。

new Config()之后调用setProtocol方法设置服务器为https服务器,同时设置证书配置。

其他的完全和http一样

如何使用MySQL?

MySQL的使用非常简单,最简单的方法如下:

  • 在入口文件处创建一个常用mysql对象: let mysqlConf = MySQLConfig.common(host, user, password, database);
  • MySQL.makeConfig(mysqlConf)
  • 如果要自定义配置则需要先new MySQLConfig(),然后调用相应的方法进行设置。

如何执行sql语句

使用MySQL.getMySQL()方法可以获取MySQL连接, 获取到连接地址之后就可以调用query方法执行sql语句了。 所有操作完成后需要调用release方法进行释放。

注意:新版本加入了quickQuery这样一个静态方法可以方便地执行sql语句

下面的示例中以一个简单的路由进行演示:

//导入相关库
import {Route, MySQL} from './../../index';

//创建一个路由
class IndexRoute extends Route {

	//获取指定年龄的用户并进行分页
	public async getUsers({age, page, every}:any) {
		age = parseInt(age);
		page = parseInt(page);
		every = parseInt(every);
		let mysql = await MySQL.getMySQL();
		console.log(mysql);
		let users = await mysql.query('select * from ?? where ? limit ?, ?', 'user', {age}, page * every, every);
		this.json(users);
		mysql.release();
	}

	//添加一个用户
	public async addUser({name, age}:any) {
		let mysql = await MySQL.getMySQL();
		let result = await mysql.query('insert into ?? (??, ??) values (?,?)', 'user', 'name', 'age', name, age);
		let id = result.insertId;
		this.json(id);
		//或者
		let {insertId} = await mysql.query('insert into ?? (??, ??) values (?,?)', 'user', 'name', 'age', name, age);
		this.json(insertId);
		mysql.release();
	}

	//测试错误捕获
	public async errorTest() {
		let mysql = MySQL.getMySQL();
		try {
			let users = await mysql.query('select * from usre ');		//故意写错user为usre
			this.json(users);
		} catch (e) {
			//打印错误
			console.log(e);
			this.json('获取用户失败');
		}
		mysql.release();
	}

	//测试事务处理
	public async testTrans() {
		let uid = 10;
		let mysql = MySQL.getMySQL();
		try {
			mysql.startTrans();
			let {insertId:head} = mysql.query('insert into ?? (??) values (?)', 'head', 'url', '/public/head/use_1.png');
			mysql.query('update ?? set ? where ?', 'user', {head}, {id: uid});
			mysql.commit();
			this.json('ok');
		} catch (e) {
			console.log(e);
			mysql.rollback();
			this.json('error');
		}
		mysql.release();
	}
}

//导出路由,以在项目入口文件中往服务器中添加该路由
export default IndexRoute;

##如何使用WebSocket

服务器已集成了websocket, 通过简单的配置即可快速使用。

  • 如果服务器是http服务器,则websocket为ws://
  • 如果服务器是https服务器,则websocket为:wss://

要使用websocket很简单,只需要如下几步。

1、配置服务器

config.setUseWebSocket(true);

2、在服务器创建完成之后配置websocket消息处理类

server.getWebSocket().setHandler(WSHandler);

##关于Websocket中消息处理类的写法

  • 需要继承自WebSocketHandler类
  • 实现onMessage方法

下面是一个例子

import {WebSocketHandler} from './../../index';

interface SocketParam {
	name: string,
	age: number
}

class WSHandler extends WebSocketHandler<SocketParam> {
	onMessage(data: any) {
		switch (data.type) {
			case 'hello':
				this.send("hello world");
				break;
			case "info":
				this.send({
					name: 'Jane',
					age: 20
				});
				break;
			default:
				this.send({
					error: 'other messages'
				});
		}
	}
}

export default WSHandler;

Keywords

FAQs

Package last updated on 22 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc