Skip to content

Dump the swagger-ui files instead of serving them #63

Description

@nmattia

I couldn't find a function for this:

-- | Dump the swagger schema and swagger-ui files to a directory.
swaggerSchemaUiDump
  :: forall dir api schema
  . (KnownSymbol dir, KnownSymbol schema, Servant.HasSwagger api)
  => FilePath -- ^ directory in which to write
  -> Proxy (Servant.SwaggerSchemaUI dir schema)
  -> Proxy api
  -> IO ()
swaggerSchemaUiDump outDir Proxy p = do
    let dir = symbolVal @dir Proxy
        schema = symbolVal @schema Proxy
        index = T.encodeUtf8 $
          T.replace "SERVANT_SWAGGER_UI_SCHEMA" (T.pack schema) $
          T.replace "SERVANT_SWAGGER_UI_DIR" (T.pack dir) $
          Servant.swaggerUiIndexTemplate
        swagger = Servant.toSwagger p
        -- The paths are prepended with '/' which confuses </>
        uiFiles = first (dropWhile (== '/')) <$> Servant.swaggerUiFiles
        prefix = case dir of
          "" -> outDir
          _ -> outDir </> dir
    let allFiles =
          [(outDir </> schema, BL.toStrict $ Aeson.encode swagger)] <>
          [(prefix </> "index.html", index)] <>
          (first (prefix </>) <$> uiFiles)

    forM_ allFiles $ \(path, content) -> do
      Directory.createDirectoryIfMissing
        True (FilePath.takeDirectory path)
      BS.writeFile path content

Happy to open a PR if you think this'll be useful to others.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions