Git Product home page Git Product logo

21gramconsulting / mediatype Goto Github PK

View Code? Open in Web Editor NEW
79.0 4.0 3.0 874 KB

This is a general purpose Swift library for a concept of typed treatment for Media Types. We use this library on clients and servers to speak the same dialect and to enjoy all the comfort strong types provide over raw strings.

Home Page: https://21gramconsulting.github.io/MediaType/

License: MIT License

Swift 92.28% JavaScript 7.72%
swift server-side-swift media-types media-type swift-library swift-package swift-libraries swift-server mime mime-types mime-parser mimetype swift-on-server 21gram

mediatype's Introduction

MediaType

Overview

MediaType is a library that can be used to create Media Types in a type-safe manner.

Mainly intended โ€“ although not limited โ€“ to be used in server-side Swift applications.

Creating Media Types

Media types are represented by the MediaType Swift type.

You can create a media type in a type-safe manner using one of the possible cases. You can also create media type instances simply by using string literals.

let mediaType: MediaType = "application/json" // is equivalent to
MediaType.application(.json())

It is also possible to create a MediaType instance from a string variable as shown in the following example.

let rawMediaType = "application/json"
let mediaType = MediaType(rawValue: rawMediaType)

Suffixes and Parameters

Media type Suffixes and Parameters are supported both via string literals and MediaType cases.

let mediaType: MediaType = "application/atom; charset=utf-8" // is equivalent to
MediaType.application(.atom(nil, ["charset": "utf-8"]))

let mediaType: MediaType = "application/atom+xml" // is equivalent to
MediaType.application(.atom(.xml))

let mediaType: MediaType = "application/atom+xml; charset=utf-8" // is equivalent to
MediaType.application(.atom(.xml, ["charset": "utf-8"]))

Trees

You can create media type trees by using either the string literal syntax, or using the other case of a particular media type.

let mediaType: MediaType = "application/vnd.efi.img" // is equivalent to
MediaType.application(.other("vnd.efi.img"))

Unregistered Media Types

Using this library you can create all the registered media types. The library is versatile enough to allow you to create practically any media type, even ones that are not registered. A few examples of such cases:

let image: MediaType = "image/svg+gzip" // is equivalent to
MediaType.image(.svg(.gzip))

let application: MediaType = "application/myApp+json" // is equivalent to
MediaType.application(.other("myApp", .json))

Using Media Types

You can use regular switch statements to test for media types and get access to their components. The following example shows various ways to treat a media type.

func isSupported(_ mediaType: MediaType) -> Bool {
  switch mediaType {
  case .application(.json(_, _)): return true
  case .application(.atom("xml", _)): return true
  case .application(let subtype):
    switch subtype {
    case .xml(_, _): return true
    default: return false
    }
  default: return false
  }
}

isSupported("application/json") // Returns: true
isSupported("application/json+xml") // Returns: true
isSupported("application/json;charset=utf-8") // Returns: true
isSupported("application/json+xml;charset=utf-8") // Returns: true

isSupported("application/atom+xml") // Returns: true
isSupported("application/atom+xml;charset=utf-8") // Returns: true
isSupported("application/atom") // Returns: false
isSupported("application/atom;charset=utf-8") // Returns: false

String Conversion

Since MediaType conforms to the CustomStringConvertible protocol it is pretty straightforward to turn an instance into a string.

You can either call the MediaType/description computed property or simply embed an instance into an interpolated string.

For example, you can request the list of available products in JSON from an imaginary store.

var request = URLRequest(url: URL(string: "https://example-store.com/products")!)
let contentType: MediaType = "application/json"

// The following two statements are equivalent
request.setValue("Content-Type", forHTTPHeaderField: "\(contentType)")
request.setValue("Content-Type", forHTTPHeaderField: contentType.description)

let (_, response) = try await URLSession.shared.data(for: request)

Media Types are Hashable

This means you can use MediaTypes in sets or dictionaries. For example, you can define the type of images your application supports like so:

let supportedImages: Set<MediaType> = ["image/png", "image/gif", "image/jpeg"]

Comparing Media Types

You can also compare media type for equality using the MediaType/==(lhs:rhs:) operator.

func canHandle(response: URLResponse) -> Bool {
  guard let mimeType = response.mimeType else { return false }
  let mediaType = MediaType(rawValue: mimeType)
  return mediaType == .application(.json())
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.