简体   繁体   中英

How to create a new Record Type using existing Record Type?

I am trying to create a simple Todo REST API using Suave. The Todo type is defined as:

type Todo =
    { id: Guid
      title: string
      isComplete: bool
      deadline: DateTime option }

This type works perfectly when using Get By Id GET /todos/{guid} and Get List GET /todos/ APIs. But when creating a new Todo item, the payload doesn't contain id property since it will be auto-generated as part of the DB operation. So, following REST API call is made:

POST /todos/

{
    "title": "Hello world",
    "isComplete": false,
    "deadline": null
}

However, the problem is JSON De-serialization breaks as the id field is not available. How to handle this scenario? Declaring id as option doesn't feel right as it is not right abstraction. In TypeScript, I can use Utility Types like Omit , Pick , etc. to create new types like:

export interface Todo {
    id: string;
    title: string;
    isComplete: boolean;
    deadline?: string
}

// Create new Type from existing type!
export type TodoInput = Omit<Todo, 'id'>;

let payload: TodoInput = {
    isComplete: false,
    title: "Hello"
}

How can I achieve similar results in F#?

You should be able to deserialize even if you don't have the id. The below works fine for me. The id will be Guid.empty.

open Newtonsoft.Json

type Todo =
    { id: Guid
      title: string
    }

let data = JsonConvert.DeserializeObject<Todo>("{\"title\":\"test\"}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM