首页 > 解决方案 > 为什么我的 POST 请求不更新正在服务的 .json 或 .js 文件?

问题描述

我知道我在这里遗漏了一些简单的东西。对我放轻松。

我有一个 graphQL 后端,它提供以下服务:

const arr = [ { id: 1, foo: 'foo' }, { id: 2, foo: 'bar' }]

然后我通过 buildSchema() 提出一个 graphql 突变请求

type Mutation {
        updateFooValue(id: Int!, foo: String!): MySchema
}

在我的 rootResolver 中,我配置了:

var root = {
    getFooQuery: getFooFunc,
    getFoosQuery: getFoosFunction,
    updateFooValue: updateFooFunc,
};

然后我将 updateFooFunc 作为:

var updateFooFunc = function ({ id, foo }) {
    arr.map(each => {
        if (each.id === id) {
            each.foo = foo;
            return each;
        }
    });
    return arr.filter(each => each.id === id)[0];
}

这一切实际上在 localhost / graphiql UI 中运行良好,但是当我检查数组时它没有更新。

昨天使用 fetch / REST post 请求的类似问题。localhost/JSON 和立即获取请求都很好,但原始 .json 文件保持不变。显然意味着重新启动服务器=您丢失任何新帐户/新聊天消息或其他任何东西-显然不是正确的方法。

我错过了什么?

标签: javascriptrestexpressgraphqlcrud

解决方案


这里有几件事要记住。

当你启动你的服务器时,变量之类arr的变量只有在服务器运行时才会保存在内存中。对变量值的更改只会改变内存中的内容——它不会更新实际代码中的内容。当您停止服务器时,变量值将从内存中释放。如果服务器再次启动,这些变量将再次具有您给它们的任何初始值。

一般来说,如果你想持久化你的数据,你需要在数据库或其他数据存储(如 Redis)中写入和读取。您还可以直接读/写文件(有关如何在节点中执行此操作的基本概述,请参阅此页面)。

顺便说一句,记住数组方法喜欢filter并且map不会改变它们被调用的数组的原始值也很重要。

const array = [1, 2, 3, 4]
array.map(item => item * 2)
console.log(array) // still shows [1, 2, 3, 4]
array.filter(item => item > 3)
console.log(array) // still shows [1, 2, 3, 4]

如果要更改原始值,则需要执行以下操作:

let array = [1, 2, 3, 4] // use let since our value will not be *constant*
array = array.map(item => item * 2)
console.log(array) // now shows [2, 4, 6, 8]
array.filter(item => item > 3)
console.log(array) // now shows [4, 6, 8]

你也可以像这样链接你的方法

array = array.map(item => item * 2).filter(item => item > 3)

把它们放在一起,如果你想让你的解析器从一个文件中读取和写入,它看起来像这样:

const fs = require('fs')

const updateFooFunc = ({ id, foo }) => {
  // assuming foo.json exists
  const valueFromFile = JSON.parse(fs.readFileSync('./foo.json'))
  const newValue = valueFromFile.map(each => {
    if (each.id === id) each.foo = foo
    return each
  })
  fs.writeFileSync(JSON.stringify('./foo.json', newValue))
  // "find" is a little better than "filter" for what you're doing
  return newValue.find(each => each.id === id) 
}

推荐阅读