Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeSpec を使い倒してる #kyotojs 22 / Use up TypeSpec

euxn23
June 28, 2024

TypeSpec を使い倒してる #kyotojs 22 / Use up TypeSpec

Kyoto.js 22 https://kyotojs.connpass.com/event/321343/
Lightning Talk

euxn23

June 28, 2024
Tweet

More Decks by euxn23

Other Decks in Programming

Transcript

  1. https://typespec.io/docs/getting-started/getting- started-http#request--response-bodies @route("/pets") namespace Pets { op list(@query skip: int32,

    @query top: int32): { @body pets: Pet[]; }; op read(@path petId: int32): { @body pet: Pet; }; @post op create(@body pet: Pet): {}; }
  2. enum Versions { v1, } model Pet = { id:

    int32; category: { id: int32; name: string; }; name: string; photoUrls: string[]; tags: { id: int32; name: string; }[]; status: "available" | "pending" | "sold"; }; @service({ title: "PetStore", }) @versioned(Versions) namespace PetStore { @operationId("findPetById") @summary("find-pet-by-id") @get findPetById(@path id: int32): { @body pet: Pet;
  3. こういうディレクトリ構造を考え る spec/ ├── main.tsp ├── namespace.tsp ├── routes/ │

    ├── pet.tsp │ ├── store.tsp │ ├── user.tsp │ └── main.tsp └── models/ ├── api-response.tsp ├── category.tsp ├── pet.tsp ├── tag.tsp ├── order.tsp ├── user.tsp └── main.tsp
  4. namespace を空で宣言する namespace.tsp を作る (各 route が namespace に子を生やしていく) import

    "@typespec/versioning"; using TypeSpec.Versioning; enum Versions { v1, } @service({ title: "PetStore", }) @versioned(Versions) namespace PetStore {}
  5. models/pet.tsp // import されたファイルに記載されている model は // global を汚染するので具体的な名前をつける model

    PetStatus = "available" | "pending" | "sold"; model Pet = { id: int32; category: { id: int32; name: string; }; name: string; photoUrls: string[]; tags: { id: int32; name: string; }[]; status: PetStatus; };
  6. routes/pet.tsp @route("/pet") namespace PetStore.Pet { @route("/") interface Root { @operationId("post-pet")

    @summary("Add a new pet to the store") @post post( @body pet: Pet ): { @statusCode statusCode: 200 | 405; @body pet: Pet; }; @operationId("put-pet") @summary("Update an existing pet") @put put( @body pet: Pet ): { @statusCode statusCode: 200 | 400 | 404 | 405; @body pet: Pet; }; }
  7. @route("/{id}") namespace Id { @route("/") interface Root { @operationId("get-pet-by-id") @summary("Find

    pet by ID") @get get( @doc("ID of pet to return") @path id: string ): { @statusCode statusCode: 200 | 400 | 404; @body pet: Pet; }; @operationId("post-pet-by-id") @summary("Update a pet in the store with form data") @post post( @header `content-type`: "multipart/form-data", @path id: string @multipartBody body: { name: HttpPart<string>;