CosmicMind / Graph

Graph is a semantic database that is used to create data-driven applications.
http://cosmicmind.com
MIT License
873 stars 72 forks source link

Added Codable support for Node. #152

Closed OrkhanAlikhanov closed 6 years ago

OrkhanAlikhanov commented 6 years ago

Added Codable support for Entity, Relationship and Actions. #144 Compiles successfully:

struct CodableGraph: Codable {
  var entity: Entity
  var relationship: Relationship
  var action: Relationship
}

Encoding:

let entity = Entity("User")
entity.name = "Orkhan"
entity.age = 20
entity.url = URL(string: "http://cosmicmind.com")!
entity.array = [-1, "2", Date(), Decimal(12.34)]
entity.dictionary = ["test": entity.array as? [Any]]

entity.add(tags: ["Swift", "iOS"])
entity.add(to: ["Programming", "Religion"])

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
encoder.dateEncodingStrategy = .iso8601
var data = try! encoder.encode(entity)
print(String(data: data, encoding: .utf8)!)

Prints:

{
  "tags" : [
    "iOS",
    "Swift"
  ],
  "properties" : {
    "age" : 20,
    "array" : [
      -1,
      "2",
      "2018-08-14T21:24:15Z",
      12.34
    ],
    "name" : "Orkhan",
    "dictionary" : {
      "test" : [
        -1,
        "2",
        "2018-08-14T21:24:15Z",
        12.34
      ]
    },
    "url" : "http:\/\/cosmicmind.com"
  },
  "createdDate" : "2018-08-14T21:24:15Z",
  "type" : "User",
  "groups" : [
    "Programming",
    "Religion"
  ]
}

Decoding: Graph (name or instance) to decode into can be provided via decoder's userInfo. If not provided, will use default Graph.

let json = "{ type: \"User\" }"
let data = json.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.userInfo[.graph] = "CodableGraph"
// decoder.userInfo[.graph] = Graph(name: "CodableGraph")
// decoder.userInfo[.graph] = nil // will use default Graph store

let entity = try! decoder.decode(Entity.self, from: data)