node.js - Node/Express 应用程序的模型文件
问题描述
我正在使用 Azure Cosmos DB 后端构建 Node/Express 应用程序。目前我使数据库调用的代码存在于 app.js 文件中,并且应用程序中的数据库文件仅在应用程序重新启动时刷新。我想我需要将我的数据库代码移动到模型中,以便我可以更轻松地调用函数与数据库进行交互。这是正确的方法吗?如果是这样,任何关于如何移动代码的提示都值得赞赏。
这是我的 app.js 文件中当前用于 cosmos db 的代码:
//Create New CosmosClient
const endpoint = config.endpoint;
const key = config.key;
const client = new CosmosClient({ endpoint, key });
const HttpStatusCodes = { NOTFOUND: 404 };
const databaseId = config.database.id;
const containerId = config.container.id;
const partitionKey = { kind: "Hash", paths: ["/state"] };
/**
* Create the database if it does not exist
*/
async function createDatabase() {
const { database } = await client.databases.createIfNotExists({ id: databaseId });
console.log(`Created database:\n${database.id}\n`);
}
/**
* Read the database definition
*/
async function readDatabase() {
// const { body: databaseDefinition } = await client.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
/**
* Create the container if it does not exist
*/
async function createContainer() {
const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId, partitionKey }, { offerThroughput: 400 });
console.log(`Created container:\n${config.container.id}\n`);
}
/**
* Read the container definition
*/
async function readContainer() {
const { resource: containerDefinition } = await client.database(databaseId).container(containerId).read();
console.log(`Reading container:\n${containerDefinition.id}\n`);
}
/**
* Exit the app with a prompt
* @param {message} message - The message to display
*/
function exit(message) {
console.log(message);
console.log('Press any key to exit');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
}
var newdb = createDatabase()
// .then(() => readDatabase())
.then(() => createContainer())
.then(() => readContainer())
.then(() => queryContainer())
.then(() => { exit(`Completed successfully`); })
.catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
/**
* Query the container using SQL
*/
async function queryContainer() {
console.log(`Querying container:\n${config.container.id}`);
// query to return all completed items
const querySpec = {
query: "SELECT r.id, r.Temp, r.DateTime, r.Sensor, r.Device FROM root r",
parameters: [
{
name: "@completed",
value: false
}
]
};
const { resources } = await client.database(databaseId).container(containerId).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
for (var queryResult of resources) {
let dataString = JSON.stringify(queryResult);
// console.log(`\tQuery returned ${dataString}\n`)
var ojb = JSON.parse(dataString)
resultString.push(ojb)
// console.log(resultString)
}
app.locals.resultString = resultString;
};
C
解决方案
您通常可以通过这种方式构建您的应用程序。
src
│ app.js # App entry point
└───api # Express route controllers for all the endpoints of the app
└───config # Environment variables and configuration related stuff
└───models # Database models
└───routes # All the routes
└───controllers # All the functions holds the business logic
此应用程序的结帐代码: https ://github.com/pprathameshmore/QuoteGarden
推荐阅读
- css - 如何将水平滚动添加到垫子自动完成
- php - Laravel 向多个表中插入数据
- openlayers - OpenLayers:定期更新瓦片层
- java - 如何在 Spring Boot 中启用/禁用特定的休息端点?
- xml - 从 xsl 生成的文档中推断数据
- angular - 如何从Angular 8中url中的查询参数中检索对象
- android - Android - 由于 Resources$NotFoundException 而导致的 RuntimeException
- ruby-on-rails - 我们如何在 20 天内使用 Ruby on Rails 开发电子商务网站并从头开始使其功能齐全?
- python - 从 selenium 重定向到最终 url 失败
- javascript - 保留鼠标移动的不透明度 - 画布