prismatic-io / spectral

Prismatic's typescript library for custom components
https://prismatic.io/docs/spectral/custom-component-library
35 stars 2 forks source link

Add cleanObject util function #188

Closed taylorreece closed 6 months ago

taylorreece commented 6 months ago

When sending payloads via HTTP client to an API, many paramaters are optional and we end up needing a series of spread operators when constructing the request payload. For example,

   const body: CreateListBody = {
      name,
      ...(content && content.length && { content }),
      ...(dueDate !== undefined && { due_date: dueDate }),
      due_date_time: dueDateTime,
      ...(priority !== undefined && { priority }),
      ...(assigneeInt !== undefined && { assignee: assigneeInt }),
      ...(status && status.length && { status }),
    };

This could be simplified with the new cleanObject function:

const body: CreateListBody = util.types.cleanObject({
   name,
   content,
   due_date: dueDate,
   due_date_time: dueDateTime,
   priority,
   assignee: assigneeInt,
   status
})

The cleanObject function defaults to removing properties with values undefined, null or "", but any predicate can be passed in. For example:

cleanObject({foo: 1, bar: 2, baz: 3}, v => v % 2 === 0)
// { foo: 1, baz: 3 }