javascript - 如何在另一个文件中制作模型
问题描述
我是初学者,试图将模型转移到另一个文件,它对我不起作用,建议我如何正确地做到这一点。这个问题可能看起来很傻,但如果我知道答案,我就不会问了。
文件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
解决方案
您在这里有两个单独的问题,将您的代码分离到不同的文件中,并将该数据保存或持久保存在某个地方,在这种情况下是一个文件。
您必须创建类似于数据模型的东西,然后必须将其导入其他代码中。
// 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))
}
所以想法是有一个模型负责管理数据、检索和保存数据,然后在主控制器中导入和使用这些方法。上面的代码并不完美,只是为了告诉你如何思考它。
推荐阅读
- flutter - 如何从函数返回上传流对象
- reactjs - useStyles 钩子在 Material-ui 中不起作用
- jsx - HTML中空标签的目的是什么?
- javascript - webview 中的 mediaDevices.getUserMedia 权限被拒绝
- javascript - 在图表中显示分组数据(不同颜色)的图例
- python-3.x - 如何将大图像数据集转换为 csv 文件?
- discord.py - Discord.py:浏览特定频道的历史,选择随机消息并发送它的链接
- wget - wget:如何排除某些已知之外的子域?
- android - React Native Android:找不到标签-1的视图管理器可能是由React Native Reanimated引起的
- mysql - 在 MySQL 中连续存储每个产品的时间序列数据的最佳方法