main codecov

什么是 URLRouter 📟

URLRouter 提供了一种在 Swift 中管理多个 URL 端点的简便方法。 它提供了一个简单的界面来管理多个端点,并允许开发人员以统一的方式与它们进行交互。 它还为开发人员提供了一种创建自定义端点 DSL (领域特定语言) 的方法,并管理每个端点的设置。 此外,它还提供了一种跟踪每个端点状态的方法,并轻松检测已进行的任何更改或更新。

类似于 Swift Evolution 的 Regex builder DSL,URL 字符串字面量和一个更强大的模式结果构建器,以帮助 Swift URL 字符串处理快速、简单且避免错误。最终,使用 URLRouter,更改很容易被检测到,并且对维护很有用。

🤔 如果您有任何疑问,请在此处提问。
💡 在此处分享您的想法。

安装 📦

配置 URLRouter 📝

实现 URLs 命名空间

import URLRouter

public enum URLs: URLRoutable {
  ...
}

HttpHeader 声明

Request {
  ...
  Header {
    Field("HEADERVALUE", forKey: "HEADERKEY")
    Field("HEADERVALUE1", forKey: "HEADERKEY1")
    Field("HEADERVALUE2", forKey: "HEADERKEY2")
    ...
  }
  ...
}
Request {
  ...
  Header([
    "HEADERKEY": "HEADERVALUE",
    "HEADERKEY1": "HEADERVALUE1",
    "HEADERKEY2": "HEADERVALUE2",
    ...
  ])
  ...
}

HttpBody 声明

Request {
  ...
  Body {
    Field("VALUE", forKey: "KEY")
    Field("VALUE1", forKey: "KEY1")
    Field("VALUE2", forKey: "KEY2")
    ...
  }
  ...
}
Request {
  ...
  Body([
    "KEY": "VALUE",
    "KEY1": "VALUE1",
    "KEY2": "VALUE2",
    ...
  ])
  ...
}

HttpMethod 声明

Request {
  ...
  Method(.get)
  ...
}
Request {
  ...
  Method.get
  ...
}

URL 声明

Request {
  ...
  URL("https://www.baseurl.com/comments?postId=1")
  ...
}
Request {
  ...
  URL {
    Scheme(.https)
    Host("www.baseurl.com")
    Path("comments")
    Query("postId", value: "1")
  }
  ...
}
// https://www.baseurl.com/comments?postId=1
Request {
  BaseURL("https://www.baseurl.com")
  URL {
    Path("comments")
    Query("postId", value: "1")
  }
}
// https://www.baseurl.com/comments?postId=1

Router {
  BaseURL("https://www.baseurl.com")
  Request {
    URL {
      Scheme(.https)
      Host("www.overrideurl.com")
      Path("comments")
      Query("postId", value: "1")
    }
  }
}
// https://www.overrideurl.com/comments?postId=1

URL Scheme 声明

Request {
  ...
  URL {
    Scheme(.https)
    ...
  }
  ...
}
Request {
  ...
  URL {
    Scheme.https
    ...
  }
  ...
}

URL Query 声明

Request {
  ...
  URL {
    Query(
      [
        "first": "firstQuery",
        "second": "secondQuery",
        ...
      ]
    )
  }
  ...
}
Request {
  ...
  URL {
    Query("test", value: "query")
    Query("test", value: "query")
    ...
  }
  ...
}
Request {
  ...
  URL {
    Query {
      Field("firstQuery", forKey: "first")
      Field("secondQuery", forKey: "second")
      ...
    }
    ...
  }
  ...
}

如何在实际项目配置和使用 URLRouter

import URLRouter

enum URLs: URLRoutable {
  // DOC: https://githubdocs.cn/ko/rest/repos/repos?apiVersion=2022-11-28#list-organization-repositories
  case listOrganizationRepositories(organizationName: String)
  // DOC: https://githubdocs.cn/ko/rest/repos/repos?apiVersion=2022-11-28#create-an-organization-repository
  case createAnOrganizationRepository(organizationName: String, repositoryInfo: RepositoryInfo)
  // DOC: https://githubdocs.cn/ko/rest/search?apiVersion=2022-11-28#search-repositories
  case searchRepositories(query: String)
  case deeplink(path: String = "home")

  struct RepositoryInfo {
    let name: String
    let description: String
    let homePage: String
    let `private`: Bool
    let hasIssues: Bool
    let hasProjects: Bool
    let hasWiki: Bool
  }
  
  var router: URLRouter {
    URLRouter {
      BaseURL("http://api.github.com")
      switch self {
      case let .listOrganizationRepositories(organizationName):
        Request {
          Method.post
          Header {
            Field("application/vnd.github+json", forKey: "Accept")
            Field("Bearer <YOUR-TOKEN>", forKey: "Authorization")
            Field("2022-11-28", forKey: "X-GitHub-Api-Version")
          }
          URL {
            Path("orgs/\(organizationName)/repos")
          }
        }
      case let .createAnOrganizationRepository(organizationName, repositoryInfo):
        Request {
          Method.post
          Header {
            Field("application/vnd.github+json", forKey: "Accept")
            Field("Bearer <YOUR-TOKEN>", forKey: "Authorization")
            Field("2022-11-28", forKey: "X-GitHub-Api-Version")
          }
          URL {
            Path("orgs/\(organizationName)/repos")
          }
          Body {
            Field(repositoryInfo.name, forKey: "name")
            Field(repositoryInfo.description, forKey: "description")
            Field(repositoryInfo.homePage, forKey: "homepage")
            Field(repositoryInfo.private, forKey: "private")
            Field(repositoryInfo.hasIssues, forKey: "has_issues")
            Field(repositoryInfo.hasProjects, forKey: "has_projects")
            Field(repositoryInfo.hasWiki, forKey: "has_wiki")
          }
        }
      case let .searchRepositories(query):
        Request {
          Method.get
          Header {
            Field("application/vnd.github+json", forKey: "Accept")
            Field("Bearer <YOUR-TOKEN>", forKey: "Authorization")
            Field("2022-11-28", forKey: "X-GitHub-Api-Version")
          }
          URL {
            Path("search/repositories")
            Query("q", value: query)
          }
        }
      case let .deeplink(path):
        URL {
          Scheme.custom("example-deeplink")
          Host("detail")
          Path(path)
          Query {
            Field("postId", forKey: "1")
            Field("createdAt", forKey: "2021-04-27T04:39:54.261Z")
          }
        }
      }
    }
  }
}

// http://api.github.com/orgs/organization/repos
let listOrganizationRepositoriesUrl = URLs.listOrganizationRepositories(organizationName: "organization").router?.urlRequest?.url

// http://api.github.com/search/repositories?q=urlrouter
let searchRepositoriesUrl = URLs.searchRepositories(query: "urlrouter").router?.urlRequest?.url

// example-deeplink://detail/comments?1=postId&2021-04-27T04:39:54.261Z=createdA
let deeplink = URLs.deeplink(path: "detail").router.url
let repositoryInfo: URLs.RepositoryInfo = .init(name: "Hello-World", description: "This is your first repository", homePage: "https://github.com", private: false, hasIssues: true, hasProjects: true, hasWiki: false)
let request = URLs.createAnOrganizationRepository(organizationName: "SomeOrganization", repositoryInfo: repositoryInfo).router?.urlRequest

URLSession.shared.dataTask(with: request) { data, response, error in
...
class AppDelegate: UIResponder, UIApplicationDelegate {
  ... 
  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
    let detailDeeplink = URLs.deeplink(path: "detail").router.url
    if detailDeeplink == url {
      ...
    }
  ...

许可证

URLRouter 基于 MIT 许可证。 有关更多信息,请参见 LICENSE 文件。


GitHub release (latest SemVer) Twitter Follow @devyhan93