首页 > 解决方案 > 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

标签: node.jsexpressazure-cosmosdb

解决方案


您通常可以通过这种方式构建您的应用程序。

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


推荐阅读