Skip to content

How to convert Cloud Code params from/to GraphQL #6596

Closed
@Setti7

Description

@Setti7

I'm trying to create a custom object from a Cloud Code using GraphQL, but I'm having trouble converting the fields from/to it.

For example, when creating an object that has a relation, we have the options to link and to createAndLink a new child object. How could I achive the same, but from inside a cloud code function, receiving the params in GraphQL and sending the response as GraphlQL too? I'm doing it field-by-field manually but it seems wrong.

Parse.Cloud.define('initOrder', async (req, res) => {
  /// Inputs
  ///   - address: AddressPointerInput!
  ///   - products: [CreateOrderItemFieldsInput!]!

  console.log(req.params.products)

  // Create order
  let order = new Parse.Object('Order')
  let orderItemsRelation = order.relation('products')

  // Setting required fields
  let user = new Parse.Object('_User')
  user.id = 'Lkwpbo84eg' // from session

  let store = new Parse.Object('Store')
  store.id = 'qmKKCBVqXG' // would be another param

  let paymentMethod = new Parse.Object('PaymentMethod')
  paymentMethod.id = 'UOZrC98GJE' // another param

  order.set('orderStatus', 'draft')
  order.set('buyer', user)
  order.set('store', store)
  order.set('paymentMethod', paymentMethod)

  /// Get Address from input
  let address
  if ('link' in req.params.address) {
    address = new Parse.Object('Address')
    address.id = req.params.address.link
  } else if ('createAndLink' in req.params.address) {
    // Create and link to order

    // Do I need to manually set all those address fields? What is the best way
    // to create an object directly from params when using graphql?
  }

  order.set('address', address)

  // Create orderItems
  req.params.products.forEach(async (product) => {
    let newOrderItem = new Parse.Object('OrderItem')
    let newProduct = new Parse.Object('Gallon')

    newProduct.id = product.product.link

    newOrderItem.set('amount', 10)
    newOrderItem.set('product', newProduct)

    let savedOrderitem = await newOrderItem.save()

    // For some reason the orderItems aren't being added to the relation.
    orderItemsRelation.add(savedOrderitem)
  })

  const saved = await order.save()
  console.log(saved.toJSON())

  /// When creating an object of a generated class with graphql, the return type
  // is actually CreateOrderPayload. How can I return such thing?
  return saved
})

Are there any examples on how to do something similar? I found this, but the examples are so simple it does not help me much.

Full project code here

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:bugImpaired feature or lacking behavior that is likely assumedtype:featureNew feature or improvement of existing feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions