如何使用 JS 生成的数据库将对象推送到 json-server 中的数组?
How to push objects to an array in json-server with a database generated in JS?
我有一个 json-server 应用程序 运行,它在启动时使用 JS 动态生成数据库。
我创建的数据被包装到一个 'users' 对象中,如下所示:
{
"users": [
{
"id": "user_id_0",
"email": "Andy_Cummerata@hotmail.com",
"first_name": "Consuelo",
"last_name": "Labadie",
"last_login_time": 1638643810,
"role": "Manager"
},
{
"id": "user_id_1",
"email": "Ricardo_Jacobs45@yahoo.com",
"first_name": "Albina",
"last_name": "Nienow",
"last_login_time": 1637479536,
"role": "User"
}
],
"Page": 1,
"PageSize": 10,
"Total": 10
}
我希望能够将新用户推送到该数组。因为我渲染我的响应来包装它,所以如果我只使用本机 POST,请求就会失败。所以我想为 编写自己的函数,但我不知道如何访问和修改我创建的数据库?
如何创建将数据发送到动态生成的数据库的函数?
以下是我的其余文件,以备不时之需。
文件:db.js
var faker = require('faker');
var utils = require('../utils.js');
const users_created = 10
module.exports = function () {
const data = { users: [] }
for (var i = 0; i < users_created; i++) {
data.users.push({
id: "user_id_" + i,
email: faker.internet.email(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
last_login_time: utils.string_to_oom_epoch(faker.date.recent(days = 40).toISOString().replace('Z', '')),
role: faker.helpers.randomize(['Admin', 'Manager', 'User'])
})
}
return data;
}
文件:server.js
const jsonServer = require('json-server');
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
router.render = (req, res) => {
if (req.url.startsWith('/generic_users_list')) {
page = parseInt(req.query.page)
pageSize = parseInt(req.query.pagesize)
filter_email = req.query.email
users = res.locals.data.users
if (filter_email !== undefined) {
filtered_users = []
for (var i = 0; i < users.length; i++)
if (users[i].email.toLowerCase() == filter_email.toLowerCase())
filtered_users.push(users[i])
users = filtered_users
}
if (!isNaN(pageSize)) {
res.jsonp({
users: users.slice(page * pageSize, (page + 1) * pageSize),
Page: page,
PageSize: pageSize,
Total: users.length
})
} else {
res.jsonp({
users: users,
Page: 1,
PageSize: users.length,
Total: users.length
})
}
} else {
res.jsonp(res.locals.data)
}
}
server.post('/generic_users_list', (req, res) => {
new_user = {
id: req.body.id,
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
last_login_time: req.body.last_login_time,
role: req.body.role
}
// WHAT DO I HAVE TO DO HERE TO ADD 'new_user' TO MY DATABASE?
})
server.use(router)
server.listen(port = 3000, () => {
console.log("port")
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
您可以将 users
数组提取出导出范围并将其定义为常量。这样它就存在于内存中,您可以向其中添加项目。您只需要导出另一个函数,这可能会将用户添加到您的内存数据库中。
var faker = require('faker');
var utils = require('../utils.js');
const users_created = 10
const data = { users: [] }
let next_id = users_created;
function initDb() {
for (var i = 0; i < users_created; i++) {
data.users.push({
id: "user_id_" + i,
email: faker.internet.email(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
last_login_time: utils.string_to_oom_epoch(faker.date.recent(days = 40).toISOString().replace('Z', '')),
role: faker.helpers.randomize(['Admin', 'Manager', 'User'])
})
}
return data;
}
function addUser(user) {
user.id = "user_id_" + next_id++;
data.users.push(user);
}
module.exports = {
initDb,
addUser,
data
}
const jsonServer = require('json-server');
const server = jsonServer.create()
const user_db = require('./db.js')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
user_db.initDb()
const router = jsonServer.router(user_db.data)
router.render = (req, res) => {
if (req.url.startsWith('/generic_users_list')) {
page = parseInt(req.query.page)
pageSize = parseInt(req.query.pagesize)
filter_email = req.query.email
users = res.locals.data.users
if (filter_email !== undefined) {
filtered_users = []
for (var i = 0; i < users.length; i++)
if (users[i].email.toLowerCase() == filter_email.toLowerCase())
filtered_users.push(users[i])
users = filtered_users
}
if (!isNaN(pageSize)) {
res.jsonp({
users: users.slice(page * pageSize, (page + 1) * pageSize),
Page: page,
PageSize: pageSize,
Total: users.length
})
} else {
res.jsonp({
users: users,
Page: 1,
PageSize: users.length,
Total: users.length
})
}
} else {
res.jsonp(res.locals.data)
}
}
server.post('/generic_users_list', (req, res) => {
new_user = {
id: req.body.id,
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
last_login_time: req.body.last_login_time,
role: req.body.role
}
user_db.addUser(new_user)
})
server.use(router)
server.listen(port = 3000, () => {
console.log("port")
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
我有一个 json-server 应用程序 运行,它在启动时使用 JS 动态生成数据库。 我创建的数据被包装到一个 'users' 对象中,如下所示:
{
"users": [
{
"id": "user_id_0",
"email": "Andy_Cummerata@hotmail.com",
"first_name": "Consuelo",
"last_name": "Labadie",
"last_login_time": 1638643810,
"role": "Manager"
},
{
"id": "user_id_1",
"email": "Ricardo_Jacobs45@yahoo.com",
"first_name": "Albina",
"last_name": "Nienow",
"last_login_time": 1637479536,
"role": "User"
}
],
"Page": 1,
"PageSize": 10,
"Total": 10
}
我希望能够将新用户推送到该数组。因为我渲染我的响应来包装它,所以如果我只使用本机 POST,请求就会失败。所以我想为 编写自己的函数,但我不知道如何访问和修改我创建的数据库?
如何创建将数据发送到动态生成的数据库的函数?
以下是我的其余文件,以备不时之需。
文件:db.js
var faker = require('faker');
var utils = require('../utils.js');
const users_created = 10
module.exports = function () {
const data = { users: [] }
for (var i = 0; i < users_created; i++) {
data.users.push({
id: "user_id_" + i,
email: faker.internet.email(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
last_login_time: utils.string_to_oom_epoch(faker.date.recent(days = 40).toISOString().replace('Z', '')),
role: faker.helpers.randomize(['Admin', 'Manager', 'User'])
})
}
return data;
}
文件:server.js
const jsonServer = require('json-server');
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
router.render = (req, res) => {
if (req.url.startsWith('/generic_users_list')) {
page = parseInt(req.query.page)
pageSize = parseInt(req.query.pagesize)
filter_email = req.query.email
users = res.locals.data.users
if (filter_email !== undefined) {
filtered_users = []
for (var i = 0; i < users.length; i++)
if (users[i].email.toLowerCase() == filter_email.toLowerCase())
filtered_users.push(users[i])
users = filtered_users
}
if (!isNaN(pageSize)) {
res.jsonp({
users: users.slice(page * pageSize, (page + 1) * pageSize),
Page: page,
PageSize: pageSize,
Total: users.length
})
} else {
res.jsonp({
users: users,
Page: 1,
PageSize: users.length,
Total: users.length
})
}
} else {
res.jsonp(res.locals.data)
}
}
server.post('/generic_users_list', (req, res) => {
new_user = {
id: req.body.id,
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
last_login_time: req.body.last_login_time,
role: req.body.role
}
// WHAT DO I HAVE TO DO HERE TO ADD 'new_user' TO MY DATABASE?
})
server.use(router)
server.listen(port = 3000, () => {
console.log("port")
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
您可以将 users
数组提取出导出范围并将其定义为常量。这样它就存在于内存中,您可以向其中添加项目。您只需要导出另一个函数,这可能会将用户添加到您的内存数据库中。
var faker = require('faker');
var utils = require('../utils.js');
const users_created = 10
const data = { users: [] }
let next_id = users_created;
function initDb() {
for (var i = 0; i < users_created; i++) {
data.users.push({
id: "user_id_" + i,
email: faker.internet.email(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
last_login_time: utils.string_to_oom_epoch(faker.date.recent(days = 40).toISOString().replace('Z', '')),
role: faker.helpers.randomize(['Admin', 'Manager', 'User'])
})
}
return data;
}
function addUser(user) {
user.id = "user_id_" + next_id++;
data.users.push(user);
}
module.exports = {
initDb,
addUser,
data
}
const jsonServer = require('json-server');
const server = jsonServer.create()
const user_db = require('./db.js')
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
user_db.initDb()
const router = jsonServer.router(user_db.data)
router.render = (req, res) => {
if (req.url.startsWith('/generic_users_list')) {
page = parseInt(req.query.page)
pageSize = parseInt(req.query.pagesize)
filter_email = req.query.email
users = res.locals.data.users
if (filter_email !== undefined) {
filtered_users = []
for (var i = 0; i < users.length; i++)
if (users[i].email.toLowerCase() == filter_email.toLowerCase())
filtered_users.push(users[i])
users = filtered_users
}
if (!isNaN(pageSize)) {
res.jsonp({
users: users.slice(page * pageSize, (page + 1) * pageSize),
Page: page,
PageSize: pageSize,
Total: users.length
})
} else {
res.jsonp({
users: users,
Page: 1,
PageSize: users.length,
Total: users.length
})
}
} else {
res.jsonp(res.locals.data)
}
}
server.post('/generic_users_list', (req, res) => {
new_user = {
id: req.body.id,
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
last_login_time: req.body.last_login_time,
role: req.body.role
}
user_db.addUser(new_user)
})
server.use(router)
server.listen(port = 3000, () => {
console.log("port")
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})