You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This advanced feature may not ever be useful, but if you find yourself in the situation of dealing with an API that does not 100% follow the **SPEC** then you might find meta-attributes are just the thing to make your entities more natural to work with.
532
+
533
+
Suppose, for example, you are presented with the unfortunate situation where a piece of information you need is only available as part of the `Id` of an entity. Perhaps a user's `Id` is formatted "{integer}-{createdAt}" where "createdAt" is the unix timestamp when the user account was created. The following `UserDescription` will expose what you need as an attribute. Realistically, this code is still terrible for its error handling. Using a `Result` type and/or invariants would clean things up substantially.
534
+
535
+
```
536
+
enum UserDescription: EntityDescription {
537
+
public static var jsonType: String { return "users" }
538
+
539
+
struct Attributes: JSONAPI.Attributes {
540
+
var createdAt: (User) -> Date {
541
+
return { user in
542
+
let components = user.id.rawValue.split(separator: "-")
543
+
544
+
guard components.count == 2 else {
545
+
assertionFailure()
546
+
return Date()
547
+
}
548
+
549
+
let timestamp = TimeInterval(components[1])
550
+
551
+
guard let date = timestamp.map(Date.init(timeIntervalSince1970:)) else {
552
+
assertionFailure()
553
+
return Date()
554
+
}
555
+
556
+
return date
557
+
}
558
+
}
559
+
}
560
+
561
+
typealias Relationships = NoRelationships
562
+
}
563
+
564
+
typealias User = JSONAPI.Entity<UserDescription, NoMetadata, NoLinks, String>
565
+
```
566
+
567
+
Given a value `user` of the above entity type, you can access the `createdAt` attribute just like you would any other:
568
+
569
+
```
570
+
let createdAt = user[\.createdAt]
571
+
```
572
+
573
+
This works because `createdAt` is defined in the form: `var {name}: ({Entity}) -> {Value}` where `{Entity}` is the `JSONAPI.Entity` described by the `EntityDescription` containing the meta-attribute.
574
+
529
575
## Example
530
576
The following serves as a sort of pseudo-example. It skips server/client implementation details not related to JSON:API but still gives a more complete picture of what an implementation using this framework might look like. You can play with this example code in the Playground provided with this repo.
0 commit comments