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

时间:2018-09-25 10:45:11

标签: javascript rest express graphql crud

我知道我在这里缺少一些简单的东西。对我好一点。

我有一个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发布请求的类似问题。本地主机/ JSON和立即提取要求很好,但原始的.json文件保持不变。显然,这意味着重新启动服务器=您丢失了任何新帐户/新的聊天消息或其他内容-因此,显然显然不是正确的方法。

我想念什么?

1 个答案:

答案 0 :(得分:1)

这里有两件事要记住。

启动服务器时,仅在服务器运行时,arr之类的变量才会保留在内存中。变量值的更改只会更改内存中的内容,而不会更新实际代码中的内容。当您停止服务器时,变量值将从内存中释放。如果再次启动服务器,这些变量将再次具有您为其赋予的初始值。

通常,如果要持久数据,则需要将其写入数据库或其他一些数据存储(例如Redis)并从中读取。您也可以直接读取/写入文件(有关如何在节点中进行操作的基本概述,请参见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) 
}