首页 > 解决方案 > 如何在另一个文件中制作模型

问题描述

我是初学者,试图将模型转移到另一个文件,它对我不起作用,建议我如何正确地做到这一点。这个问题可能看起来很傻,但如果我知道答案,我就不会问了。

文件todo.controller.js

const fs = require("fs");
const { v4: uuidv4 } = require("uuid");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
class todoController { 
async createTodo(req, res) {
    req.on("data", (data) => {
        const jsondata = JSON.parse(data);
        const title = jsondata.title;
        const description = jsondata.description;
        if ((title, description)) {
          todos.push({
            id: uuidv4(),
            title,
            description,
            dateOfCreate: new Date(),
            lastModified: new Date(),
            check: new Boolean(false),
          });
        fs.writeFile(
          "./data/data.json",
          JSON.stringify(todos, null, 2),
          (err) => {
            if (err) throw error;
          }
        );
      }
    });
  }}

文件todo.router.js

const url = require("url");
const todoController = require("../controllers/todo.controller");

const todoRouter = (req, res) => {
  const urlparse = url.parse(req.url, true);

  if (urlparse.pathname == "/todos" && req.method == "POST") {
    todoController.createTodo(req, res);
  }
};
module.exports = todoRouter;

这是文件data.json data.json

标签: javascriptnode.js

解决方案


您在这里有两个单独的问题,将您的代码分离到不同的文件中,并将该数据保存或持久保存在某个地方,在这种情况下是一个文件。

您必须创建类似于数据模型的东西,然后必须将其导入其他代码中。

// data.js

export const get = async () => {} // we will implement this just now

export const set = async (data) => {} // we will implement this just now

...

// controller.js

import {get, set} from './data.js' // import the methods we just created

...

const createTodo = async (req, res) => {
  req.on("data", (data) => {
    // here you can use get() if you want to use the data

    set(JSON.stringify(data)) // send data to your data model
  }
}

然后我们还必须对这些方法做一些实际的事情。

// data.js

export const get = async () => {
  // may need to use JSON.parse here depending on how you'll use it
  return fs.readFile('./data.json')
}

export const set = async (data) => {
  fs.writeFile('data.json', JSON.stringify(data))
}

所以想法是有一个模型负责管理数据、检索和保存数据,然后在主控制器中导入和使用这些方法。上面的代码并不完美,只是为了告诉你如何思考它。


推荐阅读