【问题标题】:Why dont my POST requests update the .json or .js files being served?为什么我的 POST 请求不更新正在服务的 .json 或 .js 文件?
【发布时间】:2019-02-28 23:12:38
【问题描述】:

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

我有一个提供以下服务的 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 文件保持不变。显然意味着重新启动服务器 = 你会丢失任何新帐户/新聊天消息或其他任何东西 - 所以 显然 这不是正确的方法。

我错过了什么?

【问题讨论】:

    标签: javascript rest express graphql crud


    【解决方案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) 
    }
    

    【讨论】:

    • 另外,使用根值是传入解析器的一种非常有限的方式。随着您继续探索 GraphQL,我强烈建议您最终使用 graphql-tools 并改用 makeExecutableSchema 构建您的架构。
    • 感谢@DanielRearden - 我认为我之前应该忽略的其他内容。但你说得很对。如果你想更新静态 js/json 文件,你需要涉足 fs/writeFile/Node'y 的东西。已经按照这些思路写了一些东西,现在表现良好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多