javascript - 有人可以解释一下吗 : 'create({email: emailArg} = {}) {}' ?

标签 javascript node.js graphql apollo

我还在学习 JS。做 Apollo GraphQL 教程:https://www.apollographql.com/docs/tutorial/introduction/

我不太明白这部分:findOrCreateUser({ email: emailArg } = {})

完整代码如下:

   /**
   * User can be called with an argument that includes email, but it doesn't
   * have to be. If the user is already on the context, it will use that user
   * instead
   */
  async findOrCreateUser({ email: emailArg } = {}) {
    const email =
      this.context && this.context.user ? this.context.user.email : emailArg;
    if (!email || !isEmail.validate(email)) return null;

    const users = await this.store.users.findOrCreate({ where: { email } });
    return users && users[0] ? users[0] : null;
  }

  async bookTrips({ launchIds }) {
    const userId = this.context.user.id;
    if (!userId) return;

    let results = [];

    // for each launch id, try to book the trip and add it to the results array
    // if successful
    for (const launchId of launchIds) {
      const res = await this.bookTrip({ launchId });
      if (res) results.push(res);
    }

    return results;
  }

请教育我,或者提供解释链接就可以了。谢谢。

最佳答案

findOrCreateUser({ email: emailArg } = {})

是几个原则的结合

1)对象解构

const { prop } = obj;

相当于:

const prop = obj.prop;

2) 函数参数解构

同样的事情,但对于函数的参数

function fun({ prop }) {
  console.log(prop);
}

相当于

function fun(obj) {
  console.log(obj.prop);
}

3)解构时重命名变量

function fun({ prop: newPropName }) {
  console.log(newPropName);
}

相当于

function fun(obj) {
  const newPropName = obj.prop;
  console.log(newPropName);
}

4) 默认函数参数

function fun(arg = 5) {
  console.log(arg); 
}

fun(10); // prints 10
fun(); // prints 5 since no value was passed to fun

结论:

findOrCreateUser({ email: emailArg } = {}) {
 // [...]
}

相当于

findOrCreateUser(args) {
  const emailArg = args ? args.email : {};
  // [...]
}

换句话说,它将传递给该方法的对象的 email 属性重命名为 emailArg 并使其直接可用。如果没有任何内容传递给函数,它还会将参数初始化为空对象。这是为了避免在未传递任何内容的情况下引发无法读取未定义的电子邮件

如果您需要更多上下文,请参阅以下文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names

关于javascript - 有人可以解释一下吗 : 'create({email: emailArg} = {}) {}' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57107654/

相关文章:

graphql - 如何将标题添加到 ionic 4/Apollo GraphQL App

graphql - useQuery 错误对象为 graphQLErrors 属性返回空数组

javascript - Graphql 将多个查询合并(合并)为一个?

javascript - FlipClock 重置倒计时

javascript - 控制台 kill 命令在 Ubuntu 上不起作用

node.js - Socket.IO/node.js问题: unintended disconnects

javascript - 我可以将 expressjs 配置为通过 http 提供某些页面,而通过 https 提供其他页面吗?

javascript - 从对象数组中删除对象项并在 Node js中分组

javascript - 测试 Solidity 合约时如何从 Javascript 初始化结构?

node.js - process.env 不包含 Heroku 上的配置变量