Skip to content

Commit

Permalink
get nested property
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Oct 11, 2024
1 parent 6918c11 commit c9d87bc
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions src/utils/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
import { type ReactNode } from "react"

import SyncError from "../components/SyncError"
import type { Optional, Required } from "./general"
import { type Optional, type Required, getNestedProperty } from "./general"

// -----------------------------------------------------------------------------
// Model Types
Expand Down Expand Up @@ -238,6 +238,10 @@ export function tagData<Type extends string, M extends Model<any>>(
return tags
}

function getModelId(result: Result<M, any>) {
return getNestedProperty(result, id)
}

return (result, error, arg) => {
if (!error) {
if (arg) {
Expand All @@ -257,24 +261,19 @@ export function tagData<Type extends string, M extends Model<any>>(
}

if (result) {
// The result is a model that contains the id field.
if (id in result) {
return tags([(result as Result<M, any>)[id] as ModelId])
}

// The result is an array of models that contain the id field.
if (Array.isArray(result)) {
return tags(result.map(result => result[id] as ModelId))
return tags(result.map(getModelId))
}

// The result is a model that contains the id field.
if (getModelId(result as Result<M, any>) !== undefined) {
return tags([getModelId(result as Result<M, any>)])
}

// The result is a list that contains an array of models that contain
// the id field.
return tags(
(result as ListResult<M, any>).data.map(
result => result[id] as ModelId,
),
true,
)
return tags((result as ListResult<M, any>).data.map(getModelId), true)
}
}

Expand Down

0 comments on commit c9d87bc

Please sign in to comment.