为什么我的 POST 请求不更新正在提供的 .json 或 .js 文件?

Why dont my POST requests update the .json or .js files being served?

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

我有一个提供以下服务的 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 中这一切实际上工作正常,但是当我检查数组时它没有更新。

昨天使用提取/REST post 请求时出现类似问题。 localhost/JSON 和立即获取请求很好,但原始 .json 文件保持不变。显然意味着重新启动服务器 = 你会丢失任何新的 accounts/new 聊天消息或其他任何内容 - 所以 显然 不是正确的方法。

我错过了什么?

这里有几件事要记住。

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

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

顺便说一句,记住 filtermap 等数组方法不会改变调用它们的数组的原始值也很重要。

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) 
}