<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[いたずら]]></title><description><![CDATA[Fun and functional programming]]></description><link>http://itazura.io:80/</link><image><url>http://itazura.io:80/favicon.png</url><title>いたずら</title><link>http://itazura.io:80/</link></image><generator>Ghost 3.2</generator><lastBuildDate>Thu, 03 Jul 2025 04:46:39 GMT</lastBuildDate><atom:link href="http://itazura.io:80/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Testing TanStack Router]]></title><description><![CDATA[<p>After using TanStack Router alongside TanStack Start recently, a common complaint I've seen has been: "it's good but I can't test it" and other complaints about a lack of testing examples.</p><p>So, I thought it would a good idea to put down some thoughts and examples of testing pages when</p>]]></description><link>http://itazura.io:80/testing-tanstack-router/</link><guid isPermaLink="false">683436128ac27f07e57c8d02</guid><category><![CDATA[typescript]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Mon, 26 May 2025 10:27:31 GMT</pubDate><content:encoded><![CDATA[<p>After using TanStack Router alongside TanStack Start recently, a common complaint I've seen has been: "it's good but I can't test it" and other complaints about a lack of testing examples.</p><p>So, I thought it would a good idea to put down some thoughts and examples of testing pages when using TanStack Router.</p><h3 id="simple-cases">Simple cases</h3><p>Sometimes you are testing a component that requries the Router to be available in context. The component may not do anything particularly interesting with the router, maybe it just needs the location current location for something:</p><figure class="kg-card kg-code-card"><pre><code class="language-TypeScript">import { useLocation, useRouter, type LinkProps } from "@tanstack/react-router"

// Within a component
const router = useRouter()
const { pathname } = useLocation()
</code></pre><figcaption>If you use these hooks, you will need the router within context</figcaption></figure><p>In this case, you may just get away with a blank router provider, which is pretty simple to create:</p><figure class="kg-card kg-code-card"><pre><code class="language-TypeScript">import type { PropsWithChildren } from "react"
import {
  createRootRoute,
  createRoute,
  createRouter,
  RouterProvider,
} from "@tanstack/react-router"

export const EmptyRouterProvider = (props: PropsWithChildren) =&gt; {
  const rootRoute = createRootRoute({
    component: () =&gt; props.children,
  })

  const router = createRouter({
    routeTree: rootRoute.addChildren([
      createRoute({
        path: "*",
        component: () =&gt; props.children,
        getParentRoute: () =&gt; rootRoute,
      }),
    ]),
  })

  return &lt;RouterProvider router={router} /&gt;
}</code></pre><figcaption>A simple router provider</figcaption></figure><p>Then in a test just wrap it in an <code>act</code></p><figure class="kg-card kg-code-card"><pre><code class="language-TypeScript">const view = await act(() =&gt;
      render(
        &lt;div&gt;
          &lt;EmptyRouterProvider&gt;
            &lt;MyComponentWithLocation /&gt;
          &lt;/EmptyRouterProvider&gt;
        &lt;/div&gt;
      )
    )</code></pre><figcaption>I can't remember why act is needed :(</figcaption></figure><h3 id="alternatively-avoid-using-router-hooks-in-components">Alternatively avoid using router hooks in Components</h3><p>Typically, I would try to avoid the above in tests. It's not that it's necessarily wrong, but I prefer components to have the data required passed down to them and leave any router or loading logic up to the router. This leds to having a <code>src/routes</code> folder with all the routes and <code>/src/pages</code> for the pages rendered. The <code>RouteComponent</code> within a route would be used for calling all the router or TanStack Query hooks.</p><p>For example, the simple test above could've been simplified if the component took a <code>location</code> or <code>path</code> prop. The route can make the <code>useLocation</code> call and pass the required data to a <code>Page</code></p><p>This style results in simple components that just take data (or if needs be, <code>QueryResult&lt;MyData&gt;</code>) or generic functions; which are very easy to test. This means no wrapping in QueryProviders, mocking fetch, etc. when testing the page. </p><p>This leads to all the loading and routing taking place in the route files, so we need to test the route code thoroughly. Treating those tests more like integration tests, then supplementing those tests with Playwright, Cypress, etc. So how do we write such a test?</p><h3 id="testing-routes">Testing Routes</h3><p>This requires a little more setup; thankfully, you only need to do it once. If you don't use TanStack Query then you could simplify all this.</p><p>The following snippet may be a little complex, but it sets up a router using your projects generated routes file with a QueryClient: </p><figure class="kg-card kg-code-card"><pre><code class="language-TypeScript">import { QueryClient } from "@tanstack/react-query"
import {
  createMemoryHistory,
  createRouter,
  RouterProvider,
} from "@tanstack/react-router"
import { render } from "@testing-library/react"

import { QueryProvider } from "~/integrations/tanstack/root-provider"
import { routeTree } from "~/route-tree.gen"

export function makeRouter({
  initialRoute,
  contextData = defaultContext, // Your routers context, this could be session info for example
  queryClient = makeTestQueryClient(),
}: {
  initialRoute: string
  contextData?: YourRouterContext
  queryClient?: QueryClient
}) {
  const memoryHistory = createMemoryHistory({
    initialEntries: [initialRoute],
    initialIndex: 0,
  })

  const router = createRouter({
    defaultPendingMinMs: 0,
    history: memoryHistory,
    routeTree: routeTree,
    context: {
      queryClient: queryClient,
      contextData: contextData,
    },
  })

  return router
}

export type TestRouter = ReturnType&lt;typeof makeRouter&gt;

export async function navigateToRoute(
  router: TestRouter,
  navigateProps: Parameters&lt;TestRouter["navigate"]&gt;[0]
) {
  await act(() =&gt; router.navigate(navigateProps))
}

export const makeTestQueryClient = () =&gt;
  new QueryClient({
    defaultOptions: { queries: { retry: false } },
  })

export async function renderWithRouter({
  initialRoute,
  session = emptySession,
  queryClient = makeTestQueryClient(),
}: {
  initialRoute: string
  context?: RouterContext // Your router's context!
  queryClient?: QueryClient
}) {
  const router = makeRouter({
    initialRoute,
    session,
    queryClient,
  })

  const app = render(
    &lt;QueryProvider client={queryClient}&gt;
      &lt;RouterProvider&lt;typeof router&gt; router={router} /&gt;
    &lt;/QueryProvider&gt;
  )

  await navigateToRoute(router, {
    to: initialRoute,
  })

  return {
    router,
    app,
  }
}
</code></pre><figcaption>Yeah there's a lot going on there</figcaption></figure><p>What you really need to care about in that is <code>renderWithRouter</code> which allows you to test your routes easily.</p><h4 id="a-quick-example">A quick example</h4><p>Lets imagine you have a route that prefetches data as part of it's <code>preload</code> then uses that data later. How do we test this given the above?</p><p></p><figure class="kg-card kg-code-card"><pre><code class="language-TypeScript">// This is just a helper for mocking fetch using vitest
const fetchMock = setupFetchMock() 
// Lets just
fetchMock.mockResolvedValue({
    ok: true,
    status: 200,
    json: async () =&gt; await {the_data: "is good"},
} as Response )

// Lets create our component
// We can use a real path to test search validation/etc
const { app, router } = await renderWithRouter({
	initialRoute: "/my-page?query=something",
})

// You can test the fetch call was made
expect(fetchMock).toHaveBeenCalledWith(
	expect.stringContaining(
		"/my-api/some-network-call?user-query=something"
	),
    expect.objectContaining({
        method: "GET",
        headers: { Accept: "application/json" },
  	})
)

// You test using `app` like you would in RTL. I'd only do
// minimal checks here and test the page individually:
const heading = await waitFor(() =&gt;
    app.getByRole("heading", {
    name: "The Page",
  })
)
expect(heading).toBeInTheDocument()

// Or test the router
expect(router.state.location.pathname).toBe("/my-page")
</code></pre><figcaption>That nasty helper makes life easy</figcaption></figure><p>So there you go. You are directly testing the route component here using the actual router. From here you test the page if you want via <code>app</code>, the router by accessing it, and the fetch calls (or use MSW if that's your thing)</p><p>Likewise, you get to provide the initial context. So if you use the router context for holding an auth session you can provide a fake one when testing authenticated routes, and test your navigation when no session is provided.</p><p>As mentioned prior, I prefer to split data/routing from the page itself. Stick to testing routes, context related functions, and data loading in these tests. Then use that to create a page where you can test interactivity.</p>]]></content:encoded></item><item><title><![CDATA[Type-Safety and Abstraction using Singleton Variants]]></title><description><![CDATA[Singleton Variants in Reason can be used to express stronger type safety similar to Scala's Value Classes or Haskells newtype.]]></description><link>http://itazura.io:80/type-safety-using-singleton-variants/</link><guid isPermaLink="false">5e3b891d058b9b0720688e2e</guid><category><![CDATA[reasonml]]></category><category><![CDATA[scala]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Fri, 14 Feb 2020 01:55:17 GMT</pubDate><content:encoded><![CDATA[<p>Variants are sold as one of Reason's more powerful features, often demonstrated to show polymorphic pattern matching; however, they have another interesting use case by boxing datatypes as singleton variants to create something similar to a <em>Value Class</em> or <em>newtype.</em></p><p>From working with <a href="https://dzone.com/articles/what-value-classes-is">Scala I am used to creating <em>Value Classes</em></a>, which can be compared to Haskell's <em>newtype. </em>These constructs allow the developer to express greater levels of type information and abstraction in their code, with little or no runtime performance penalty. It's possible to achieve the same effect in ReasonML with singleton variants.</p><h2 id="what-is-a-value-class">What is a Value Class?</h2><p>A value class is a simple wrapper around a primitive type that gives you more control over the input and output of functions. This has a number of benefits, such as restricting construction to validated values or simply aiding with passing around many parameters into a function.</p><p>These are very easy to construct in Scala by extending <code>AnyVal</code> </p><pre><code class="language-scala">case class Name(value: String) extends AnyVal</code></pre><p>Whilst it looks like there is an additional overhead here; after all, the <code>String</code> has been boxed inside a class which you would expect would need to be instantiated each time – in the JVM the wrapping class is removed after compilation. So there should not be a performance cost when wrapping types in this manner. There is just one minor issue, if you wish to access the underlying <code>String</code> then you have to manually access it:</p><figure class="kg-card kg-code-card"><pre><code class="language-scala">val name = Name("Cat")

println("The name is: " + name.value)</code></pre><figcaption>I almost used ++ as if I were using Reason</figcaption></figure><p>You can achieve something similar in ReasonML by boxing the type and I'll demonstrate it later.</p><h2 id="why-would-you-want-to-do-this">Why would you want to do this?</h2><p>Essentially to make your code more descriptive and to prevent mistakes. This is probably best illustrated with examples. So let us imagine you have a function type signature for a simple function to create a person:</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">let makePerson: (string, string, string, int) =&gt; unit;</code></pre><figcaption>Back to Reason</figcaption></figure><p>As simple as the definition is, it may leave you wondering about a number of things: how you know distinguish between the meaning of these fields? Which holds the first name and which the surname? Just what exactly is that <code>integer</code>? Why are there three <code>string</code> parameters?</p><p>Sure, you could probably work those questions out by looking at the output type, and yes, I deliberately left it as <code>unit</code> to make life hard. Still, this function could be storing its output in a database or mutable dictionary somewhere and <code>unit</code> could be an acceptable output type.</p><p>So in order to answer that question, you may wish to use named parameters instead. And that's a reasonable solution:</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">let makePerson: (
  ~firstName: string,
  ~surname: string, 
  ~hometown: string, 
  ~age: int
) =&gt; unit 
</code></pre><figcaption>You'd have to actually implement this to get it to compile</figcaption></figure><p>Now at least you can identify what goes where and it would be acceptable to finish here. Still, this has some minor issues that can be addressed. For example, you could accidentally pass in a name into the hometown field.</p><p>Another alternative would be to use <em>type aliases</em> for the fields, which would make the method more descriptive without the overhead of typing the labels each time:</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">type firstName = string;
type surname = string;
type hometown = string;
type age = int;

let makePerson: (
  firstName,
  surname, 
  hometown, 
  age) =&gt; unit</code></pre><figcaption>This reads rather nicely</figcaption></figure><p>Whilst very readable, this code is no safer than the original implementation. Aliases don't provide any protection and you can pass any string as any of the function's parameters.</p><p>In both solutions, the <code>string</code> type is still being used for three different things; however, in Scala is possible to abstract the <code>string</code> away by using <em>Value Classes</em>. Let's quickly demonstrate that:</p><figure class="kg-card kg-code-card"><pre><code class="language-scala">case class FirstName(value: String) extends AnyVal
case class Surname(value: String) extends AnyVal
case class Hometown(value: String) extends AnyVal
case class Age(value: String) extends AnyVal

abstract def makePerson(
  firstName: FirstName,
  surname: Surname, 
  hometown: Hometown,
  age: Age): Person
  
// Or if you simply wanted to use a constructor
case class Person(
  firstName: FirstName,
  surname: Surname, 
  hometown: Hometown,
  age: Age)</code></pre><figcaption>Mmm... Scala</figcaption></figure><p>So in the above example, unlike simple type aliases, you cannot pass a <code>FirstName</code> into say the <code>Hometown</code> field. Each of those types is independent of the primitive type it wraps.</p><h2 id="so-how-do-we-do-this-in-reason">So how do we do this in Reason?</h2><p>So how do we do this in Reason? Well, we can box the primitive types within single-argument variants.</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">type firstName = FirstName(string);
type surname = Surname(string);
type hometown = Hometown(string);
type age = Age(int);

let makePerson: (
  firstName,
  surname, 
  hometown, 
  age) =&gt; unit = (a, b, c, d) =&gt; ();</code></pre><figcaption>Aha! Single-argument variants</figcaption></figure><p>Now it isn't possible to accidentally pass in a hometown as a surname, any such mistake would cause the program to not compile. Whilst this is only a simple example, this becomes more useful the bigger your solution gets. Anywhere else in the codebase it would no longer be possible to mistake a <code>surname</code> for a <code>string</code> or an <code>age</code> for an <code>int</code>.</p><p>A common situation for this in a larger application is for <code>id</code> fields. You may end up with <code>int</code> being used for a user id, post id, account id, payment id, group id, and so on. If these types are abstracted within singleton variants, then we can differentiate between the types.</p><p>Now, at some point you will need to unbox the values from these singleton variants. You could use a switch, but that's a little long-winded. Instead, try using the handy <code>fun</code> shortcut.</p><pre><code class="language-reason">let name = FirstName("Dave");

let nameString = name |&gt; fun | FirstName(str) =&gt; str;</code></pre><p>That's nice, but there's yet another, easier way to unbox the value:</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">let FirstName(nameString) = name;

/* Now you can use `nameString` 
Js.log("The person's name is: " ++ nameString");</code></pre><figcaption>Yeah! This is even better.</figcaption></figure><h2 id="isn-t-there-a-performance-cost">Isn't there a performance cost?</h2><p>Unlike Scala, the above example does come with a penalty. There is a small cost as Reason will construct the variant as a single argument array. Accessing the value in the code above is like accessing an array using <code>myArray[0]</code>. For example the above <code>name</code> construction compiles to:</p><pre><code class="language-js">var name = /* FirstName */["Dave"];</code></pre><p>However, since release <code>7.1.0</code> we are able to use <code>unboxed</code> to get around this! What is this? Let's look at the OCaml manual:</p><blockquote>unboxed can be used on a type definition if the type is a single-field record or a concrete type with a single constructor that has a single argument. It tells the compiler to optimize the representation of the type by removing the block that represents the record or the constructor (i.e. a value of this type is physically equal to its argument). </blockquote><p>This now means a singleton variant is not compiled as an array but is instead unboxed to the underlying type. Essentially, like with Scala, the OCaml compiler will erase the singleton variant in a later stage of compilation as it's not required at runtime. To use this mark the type as <code>[@unboxed]</code> like so:</p><pre><code class="language-reason">[@unboxed]
type hometown = Hometown(string);
let tokyo = Hometown("tokyo");
</code></pre><p>This will then be unboxed from the array to a simple <code>var</code> during compilation:</p><figure class="kg-card kg-code-card"><pre><code class="language-js">var tokyo = "tokyo";
</code></pre><figcaption>No more array!</figcaption></figure><p>So no more performance penalties! According to the release notes, this can also be used to <a href="https://bucklescript.github.io/blog/2019/12/20/release-7-02">unbox singleton records </a>. Note, that whilst the release notes are for development version, this feature was released with bs-platform@7.1.0.</p><p>To give you a quick example of using singleton records:</p><pre><code class="language-reason">[@unboxed]
type hometown = {name: string};
let kyoto = {name: "kyoto"};</code></pre><p>That will compile to the following JavaScript:</p><pre><code class="language-js">var kyoto = "kyoto";
</code></pre><p>As a record it may be simplier to extract the values, there's no need for pattern matching:</p><pre><code class="language-reason">[@unboxed]
type hometown = {name: string};
let kyoto = {name: "kyoto"};

Js.log("The name is: " ++ kyoto.name);</code></pre><p>Whether you prefer to use singleton variants or records for this is a personal choice. As you can see, variants are not as clean to extract from as records, but are quicker to construct.</p>]]></content:encoded></item><item><title><![CDATA[Dependency Injection using Modules]]></title><description><![CDATA[In Reason and OCaml functors (functions from modules to modules) can be used to implement DI. This aids with writing easily testable code.]]></description><link>http://itazura.io:80/modules-for-dependency-injection/</link><guid isPermaLink="false">5e28f0cbcfe8725962a36cdd</guid><category><![CDATA[reasonml]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Tue, 28 Jan 2020 23:50:12 GMT</pubDate><content:encoded><![CDATA[<p>When I wrote my f<a href="https://github.com/RawToast/dokusho">irst project </a><em><a href="https://github.com/RawToast/dokusho">Dokusho</a></em><a href="https://github.com/RawToast/dokusho"> in ReasonML</a> I just imported modules from anywhere as that just seemed to be the way things were done. This was ok when writing a simple React frontend, but when I later wrote the more complex <a href="https://github.com/RawToast/bouken">backend for Bouken</a> it didn't scale and quickly became messy and hard to test.</p><p>I was used to using dependency injection – often known as DI – as a pattern from writing Java and Scala, which is a pattern that enables inversion of control. Or more simply put, constructing an object or module from other modules/objects and using the functions provided. </p><p>Now in ReasonML  functors – functions from modules to modules – can be used to  implement dependency injection. Functors can be used for more advanced techniques, such as creating modules that parameterise other modules; however, this is a good introduction to the module system. When I first used this technique the language server failed to understand what I was doing! Thankfully, that issue been fixed!</p><p>Why would you want to use dependency injection? Well, for example, you could have a service that uses another module to make a call to an API:</p><pre><code class="language-reason">module MyService = {
  let userAndComments = id =&gt; { 
     let user = UserApi.userById(id);
     switch(user) {
       | Some(user) =&gt; { 
       let comments = CommentsApi.fetchUserComments(id); 	
       Some({ user.name, comments });
       }
       | None =&gt; None
     }
   };
};</code></pre><p>The code probably works, but are a few issues with this:</p><ul><li>It can lead to a spiderweb of dependencies.</li><li>It can be hard to unit test, in this example you cannot test the <code>userAndComments</code> method without making a HTTP call. In order to test this module,  you would require either a mocked server or an integration test.</li></ul><p>We can use dependency injection to control what the service receives in order to facilitate easier unit testing. So how would we go about that?</p><p>First, let define a type that we can inject. This is a simple type definition for logging output.</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">module type Logger = {
  let log: string =&gt; unit;
};</code></pre><figcaption>A simple logger module type</figcaption></figure><p>Then we can create a new module that uses the `Logger` we have defined. In OCaml and Reason a module that is built from other modules is known as a <em>Functor</em>.</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">module GreetingService = (LOG: Logger) =&gt; {
  let sayHello = name =&gt; LOG.log("Hello " ++ name); 
};</code></pre><figcaption>The power of CAPS-LOCK</figcaption></figure><p>Now we can implement a <code>Logger</code> and pass it into a <code>GreetingService</code>: creating a module from another module.</p><pre><code class="language-reason">module ConsoleLogger = {
  let log = loggable =&gt; Js.Console.log(log);
};

module ConsoleGreeter = GreetingService(ConsoleLogger);

ConsoleGreeter.sayHello("World");</code></pre><p>Note that we are free to choose how the <code>Logger</code> works – it only has to match the type signature. For example, you could implement an <code>ErrorLogger</code> instead:</p><pre><code class="language-reason">module ErrorLogger = {
  let log = loggable =&gt; Js.Console.error(log);
};</code></pre><p>Effectively we have taken away control from <code>GreetingService</code> to <code>Logger</code>. Now <code>GreetingService</code> describes <em>what it wants to do</em>, but doesn't actually implement <em>how to do it</em>. This is often reffered to as <em>inversion of control. </em></p><p>When writing systems in a modern<em> </em>object-oriented style using programming languages such as Java or Kotlin, this technique is heavily used. Often you will read that you should <em>"prefer composition over inheritance" </em>and DI is used to alongside composition to create cleaner more testable code. </p><p>This pattern can be used in ReasonML (and OCaml), by using functors for dependency injection. Lets go back to the original example to demonstrate this:</p><h3 id="updating-the-original-service">Updating the Original Service</h3><p>Remember this? It's the <code>MyService</code> module from the first example.</p><pre><code class="language-reason">module MyService = {
  let userAndComments = id =&gt; { 
     let user = UserApi.userById(id);
     switch(user) {
       | Some(user) =&gt; { 
       let comments = CommentsApi.fetchUserComments(id); 	
       Some({ user.name, comments });
       }
       | None =&gt; None
     }
   };
};</code></pre><p>We can turn <code>MyService</code> into a <em>functor</em> and construct an instance by passing <em>module types</em> for <code>UserApi</code> and <code>CommentsApi</code>. </p><figure class="kg-card kg-code-card"><pre><code class="language-reason">module MyService = (Users: UserApi, Comments: CommentsApi) =&gt; {
  let userAndComments = id =&gt; { 
    let user = Users.userById(id);
    switch(user) {
      | Some(user) =&gt; { 
      let comments = Comments.fetchUserComments(id); 	
      Some({ user.name, comments });
      }
     | None =&gt; None
    }
  };
};</code></pre><figcaption>In OCaml a module that is built from other modules is known as a Functor</figcaption></figure><p>Now this module is easier to test. You can pass in stubbed versions of the modules in order to test the flow of the <code>userAndComments</code> function.</p><pre><code class="language-reason">module StubUserApi = {
  let userById = id =&gt; switch(id) {
    | 1 =&gt; Some({ name: "Test User"})
    | _ =&gt; None
  };
};

module StubCommentsApi = {
  let fetchUserComments = id =&gt; 
    { title: "Test Comment", message: "Hello" };
};</code></pre><p>Now it's easy to test the service using these simple stubbed modules:</p><pre><code class="language-reason">module UnderTest = MyService(StubUserApi, StubCommentsApi);

let result = UnderTest.userAndComments(1); // Some({ ...
let anotherResult = Undertest.userAndComment(2); // None</code></pre><p>I started using this part way through building Bouken. As previously stated, I initially imported modules from anywhere as that seemed to be the way things were done and worked for my frontend logic. Shortly afterwards, the game loop became unwieldy and needed breaking up.</p><figure class="kg-card kg-bookmark-card kg-card-hascaption"><a class="kg-bookmark-container" href="https://github.com/RawToast/bouken"><div class="kg-bookmark-content"><div class="kg-bookmark-title">RawToast/bouken</div><div class="kg-bookmark-description">React based ASCII Rogue. Contribute to RawToast/bouken development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.githubassets.com/favicon.ico"><span class="kg-bookmark-author">RawToast</span><span class="kg-bookmark-publisher">GitHub</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://avatars0.githubusercontent.com/u/8013000?s=400&amp;v=4"></div></a><figcaption>There's a link on the repository page.</figcaption></figure><p>Over time the more complex modules were broken down into smaller modules for easier testing and code management. This eventually turns into a dependency tree of module types. For example, the main game builder is defined as follows:</p><figure class="kg-card kg-code-card"><pre><code class="language-reasonml">module CreateGame: (
  Types.GameLoop, 
  Types.World, 
  Types.WorldBuilder
) =&gt; (Types.Game) = (
    GL: Types.GameLoop, 
    W: Types.World, 
    WB: Types.WorldBuilder
  ) =&gt; { };
  
// Which is build outf
module CreateGameLoop = (
  Pos: Types.Positions, 
  EL: EnemyLoop
) =&gt; { };

module CreateEnemyLoop = (
  Pos: Types.Positions, 
  Places: Types.Places, 
  World: World
) =&gt; { };</code></pre><figcaption>Why "createX"? Module types were defined elsewhere such as `module type GameLoop = { }`</figcaption></figure><p>So as demonstrated, you can use Reason's advanced module system for dependency injection – you do not need to use objects! Instead, use modules for organising your code and leave objects alone until you absolutely require open types or inheritance.</p>]]></content:encoded></item><item><title><![CDATA[Objects in ReasonML, Part 4: Structural Subtyping or Row Polymorphism]]></title><description><![CDATA[Row Polymorphism is a powerful feature of objects in OCaml/ReasonML, that you can use to get around the strict nature of Records.]]></description><link>http://itazura.io:80/objects-in-reasonml-part-4-structural-subtyping-or-row-polymorphism/</link><guid isPermaLink="false">5e2777a59eeb6d42b866de1d</guid><category><![CDATA[reasonml]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Mon, 27 Jan 2020 00:41:18 GMT</pubDate><content:encoded><![CDATA[<p>Row Polymorphism is a powerful feature of objects in OCaml/ReasonML, that you can use to get around the strict nature of Records. At the same time, as the typing is more loose, it is possible to pass in the wrong type to a function and the compiler will not be able to safe you! </p><p>Using <em>open object types</em> you can create functions or methods that accept various types that may only have a single value in common. For example, what if you wanted to require the parameter had a field called <code>name</code> but didn't care about the rest of the data? How would such an <em>open object </em>be defined?</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">type tx('named) = {
  ..
  getName: string,
} as 'named;


let tellMeYourName: tx('named) =&gt; unit = named =&gt; {
  Js.log(named#getName);
};</code></pre><figcaption>See the <code>..</code> !</figcaption></figure><p>The key to this definition is the double dot <code>..</code>, which indicates that the type is open, thus it can contain other fields and values. This means that the above snippet defines a type with a <code>getName</code> method that returns a string – and any other methods.</p><p>The next snippet demonstrates the function declared above being called with various difference types.</p><pre><code class="language-reason">class dog (name: string) = {
  as _;
  pub getName = name;
  pub talk = Js.log("Woof!");
};

let myDog = new dog("Spot");
tellMeYourName(myDog);

let makeCat = (name: string, age: int) =&gt; {
  as _;
  val mutable catName = name;
  val mutable catAge = age;
  pub getName = catName;
  pub getAge = catAge;
  pub setAge = age =&gt; catAge = age;
};

let myCat = makeCat("Cool Cat", 12);
tellMeYourName(myCat);</code></pre><p>Note that if you’d rather not have the intermediary type, you can simply define the structure in the function. This reminds me of structural typing in JavaScript.</p><pre><code class="language-reason">let tellMeYourNameAgain: { .. getName: string } =&gt; unit = 
  named =&gt; Js.log(named#getName);

tellMeYourNameAgain(myDog);
tellMeYourNameAgain(myCat);</code></pre><p>Note that if you don't include the type in the function definition,  the type for the parameter should be inferred as as open object containing <code>getName</code>. </p><pre><code class="language-reason">let tellMeYourNamez = named =&gt; {
  print_endline(named#getName);
};
// Type from sketch.sh
// let tellMeYourNamez: {.. getName: string } =&gt; unit = &lt;fun&gt;;</code></pre><p>It is not possible to pass in a record to a function with an open object parameter, but you could convert to the object type beforehand; however, writing such converters might be the same effort as using varients and pattern matching...</p><p>For now, this is the end of my short series on using objects in Reason. I do have some notes on using row polymorphism within a functional program, with any luck I'll post something this week.</p>]]></content:encoded></item><item><title><![CDATA[Objects in ReasonML, Part 3: Immutable Updates]]></title><description><![CDATA[Immutable updates of functional objects in ReasonML.]]></description><link>http://itazura.io:80/objects-in-reasonml-part-3-immutable-updates/</link><guid isPermaLink="false">5e2776a59eeb6d42b866de07</guid><category><![CDATA[reasonml]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Sat, 25 Jan 2020 13:03:07 GMT</pubDate><content:encoded><![CDATA[<p>In ReasonML records allow for immutable updates using the <em>spread operator</em>, similar to copying case classes in Scala. This is also possible with objects, allowing the creation of immutable, but updatable, objects. In OCaml, these are known as <em>functional objects</em>.</p><p>Most ReasonML developers have come across the syntax below to update immutable records:</p><pre><code class="language-reason">type cat = {name: string, age: int};

let kitten = { name: "Charles", age: 1 };

let oldCat = { ...kitten, age: 4 };</code></pre><p>A similar technique exists for objects; however, it's not so well known amongst Reason developers, as I believe it is not included in the documentation. So at first, you might attempt something like the example below, which works but quickly becomes verbose as your records grow in size:</p><pre><code class="language-reason">class immutableDog(name, age) = {
  as _;
  pub getAge: int = age;
  pub getName: string = name;
  pub setName: string =&gt; immutableDog = newName =&gt; new immutableDog(newName, age);
  pub setAge: int =&gt; immutableDog = newAge =&gt; new immutableDog(name, newAge);
};</code></pre><p>Instead, you can override values to make a new instance with only the specified updates, similar to records. The syntax is not so obvious:</p><pre><code class="language-reason">class immutableCat(name, age) = {
  as _;
  val name = name;
  val age = age;
  pub getAge: int = age;
  pub getName: string = name;
  pub setName = newName =&gt; {&lt;name: newName&gt;}; // Creates a new instance.
  pub setAge = newAge =&gt; {&lt;age: newAge&gt;};
};</code></pre><p>This technique uses the override construct <code>{&lt; ... &gt;}</code>, which returns a copy of the current object and allows you to override the value of instance variables or methods.</p><p>Lets see what it looks like in action:</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">let myImmutableCat: immutableCat = new immutableCat("Cool Cat", 5);
let myNewCat: immutableCat = myImmutableCat#setName("Dave");</code></pre><figcaption>Oooh immutables!</figcaption></figure><p>Note that in the above example, <code>myImmutableCat</code> does not change. </p><p>It is also possible to update values in the same way:</p><figure class="kg-card kg-code-card"><pre><code>class immutable = (number) =&gt; {
  as _;
  val counter = number * number;
  pub makeNegative = {&lt;counter: -counter&gt;};
  pub getCounter = counter;
};

let myImmutable = new immutable(4);
let negative = myImmutable#makeNegative;
myImmutable#getCounter // 4
negative#getCounter // -16</code></pre><figcaption>Yay more immutables!</figcaption></figure><p>Whilst this is a nice feature, the syntax could definately be improved and the functionality better documented. </p><p>And finally you're ready for the final part: <a href="http://itazura.io/objects-in-reasonml-part-4-structural-subtyping-or-row-polymorphism/">row polymorphism and structural subtyping</a>!</p>]]></content:encoded></item><item><title><![CDATA[Objects in ReasonML, Part 2: Inheritance and Virtual Classes]]></title><description><![CDATA[<p>In the first article we covered the basics of objects in ReasonML: how to define objects, classes, mutation, and encapsulation using private methods. </p><h3 id="the-polymorphic-nature-of-objects">The Polymorphic Nature of Objects</h3><p>Polymorphism is that ability for an object or method to take many forms. Essentially a function or method is polymorphic when it</p>]]></description><link>http://itazura.io:80/objects-in-reasonml-part-2-inheritance/</link><guid isPermaLink="false">5e26f9469eeb6d42b866dd44</guid><category><![CDATA[reasonml]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Fri, 24 Jan 2020 14:30:54 GMT</pubDate><content:encoded><![CDATA[<p>In the first article we covered the basics of objects in ReasonML: how to define objects, classes, mutation, and encapsulation using private methods. </p><h3 id="the-polymorphic-nature-of-objects">The Polymorphic Nature of Objects</h3><p>Polymorphism is that ability for an object or method to take many forms. Essentially a function or method is polymorphic when it can take more than one type of parameter.  </p><p>There is an interesting feature of objects where – unlike records – any object that matches the signature of a function is deemed acceptable, this makes writing polymorphism easy to achieve.  Note that can even be as undesirable, as it means methods or functions taking objects not as strict as with records: the wrong object could be passed in and the compiler may not help you!</p><p>We can create polymophic functions by using an object type as the parameter for a method. So lets create a simple type:</p><pre><code class="language-reason">type pet = {
  .
  getName: string,
  talk: unit
}</code></pre><p>Then you are free to implement this type as many times as you like.</p><pre><code class="language-reason">class cat = (name) =&gt; {
  as _;
  pub getName = String.trim(name);
  pub talk =  Js.log("Nya!");
};

class dog = (name) =&gt; {
  as _;
  pub getName = String.capitalize_ascii(name);
  pub talk =  Js.log2("Woof!", name);
};</code></pre><p>As both the <em>cat</em><strong><em> </em></strong>and <em>dog </em>classes implement the <em>pet </em>signature, we can write a function that works on <em>pet</em> and it will accept both cats and dogs:</p><pre><code class="language-reason">let myCat: cat = new cat(" Cuddles ");
let myDog: dog = new dog("spot");
let greet: pet =&gt; string = 
	p =&gt; "Hello " ++ p#getName;
let doubleGreet: string = 
	greet(myCat) ++ " and " ++ greet(myDog);</code></pre><h3 id="abstraction-using-virtual-classes">Abstraction using Virtual Classes</h3><p>Inheritance in ReasonML can be defined using <em>virtual</em> objects and methods. Essentially a <em>virtual</em> method or object is similar to an <em>abstract</em> method or class in Java — it is left undefined and has to be implemented by the inheriting class.</p><p>We can define a virtual class as follows:</p><pre><code class="language-reason">class virtual pet (name: string) = {
  as self;
  pri getName = 
    name 
    |&gt; String.trim 
    |&gt; String.capitalize_ascii;
  pub virtual talk: unit;
};

// You can't do this:
let myVirtualPet = new pet("davey");</code></pre><p>There a few things to take note of here:</p><ul><li>If class is defined as <em>virtual</em>, we cannot instantiate it.</li><li>A <em>virtual class</em> may contain private methods. These act like protected methods in Java. When defining a subclass, we will have access to them; however, once we instantiate a class we will not have access to it. This is a form of <em>abstraction</em>.</li><li>You can define concrete methods alongside <em>virtual methods</em>. In this case getName handles trimming and capitalising for us and the user no-longer has to define that functionality per class.</li></ul><h3 id="inheriting-from-a-virtual-class">Inheriting from a Virtual Class</h3><p>Instead of creating virtual classes, we have to define a new class that inherits from the virtual class. Note how in this instance we are able to access the <code>getName</code> private method from within the class definition; however, this cannot be accessed from a <code>dog</code> or <code>pet</code> object.</p><pre><code class="language-reason">class dog (name) = {
  as self;
  inherit (class pet)(name);
  pub talk = 
    Js.log(self#getName ++ ", says Woof!");
};


let myDog: pet = new dog("Spot");
myDog#talk; // prints 'Spot, says Woof!'
myDog#getName; // does not compile :(
class cat (name) = {
  as _;
  inherit (class pet)(name);
  pub talk = "Nya!");
};
let myCat: pet = new cat("Kitten");
myCat#talk; // prints 'Nya!'</code></pre><p>As you can see the <code>talk</code> method is implemented differently for both instances. Thus a pet has polymophic behaviour, unless we know which instance it actually is we are unable to determine how it behaves.</p><h3 id="overriding-a-method">Overriding a Method</h3><p>Sometimes you wish to override the functionality provided by the class you are inheriting from. This can be done by adding an exclamation mark after <code>inherit</code> , like so:</p><pre><code class="language-reason">class cat (name) = {
  as self;
  inherit (class pet)(name);
  pub talk = 
    Js.log(self#getName ++ ", says Nya!");
};
class shyCat (name) = {
  as self;
  inherit (class cat)(name);
  pub! talk = Js.log(self#getName);
};</code></pre><p>In the above example, <code>shyCat</code> ‘s talk method overrides <code>cat</code> to not include the cat’s name.</p><h3 id="multiple-inheritance-and-the-diamond-problem">Multiple Inheritance and the Diamond Problem</h3><p>Interestingly OCaml supports multiple inheritance. This is something that often needs to be treated with care as there is a chance you may run into the <a href="https://en.wikipedia.org/wiki/Multiple_inheritance" rel="noopener">diamond problem</a>:</p><blockquote>An ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have <a href="https://en.wikipedia.org/wiki/Method_overriding_%28programming%29" rel="noopener">overridden</a>, and D does not override it, then which version of the method does D inherit: that of B, or that of C?</blockquote><p>Thankfully OCaml mitigates this by enforcing that you define the inheritance in order. Thus sub-classes will take the last defined instance of a method.</p><figure class="kg-card kg-code-card"><pre><code class="language-reason">class virtual namedDave = {
  as _;
  pri getName = "Dave";
  pub virtual count: int;
};
class dog (name) = {
  as self;
  inherit (class namedDave);
  inherit! (class pet)(name);
  pub talk = Js.log(self#getName ++ ", says Woof!");
  pub count = 0;
};
class otherDog (name) = {
  as self;
  inherit (class pet)(name);
  inherit! (class namedDave);
  pub talk = Js.log(self#getName ++ ", says Woof!");
  pub count = 1;
};
let dog1 = new dog("Not Dave");
let dog2 = new otherDog("Will be called Dave");</code></pre><figcaption>No diamond issues here!</figcaption></figure><p>Next up in this little <a href="http://itazura.io/objects-in-reasonml-part-3-immutable-updates/">series about objects in Reason: immutable updates.</a></p>]]></content:encoded></item><item><title><![CDATA[Objects in ReasonML, Part 1: Objects and Classes​]]></title><description><![CDATA[The basics of using objects and classes in ReasonML. ]]></description><link>http://itazura.io:80/objects-in-reasonml-part-1-objects-and-classes/</link><guid isPermaLink="false">5e26496d174b030abe5ebc56</guid><category><![CDATA[reasonml]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Thu, 23 Jan 2020 00:04:00 GMT</pubDate><content:encoded><![CDATA[<p>ReasonML is an alternative syntax for OCaml by Facebook, that has gained traction as a language for writing frontends alongside React. It has impressive type inference, blazing fast compile times, and a powerful module system.</p><p>As Reason is a syntax for OCaml, it also comes with support for object-oriented programming. I get the impression that object-oriented programming is typically not recommended in OCaml, and this seems to also apply to ReasonML. Hence there is little documentation for using objects in Reason ML -- there's just a <a href="https://reasonml.github.io/docs/en/object" rel="nofollow noopener noopener">single page in the official documentation</a>.</p><p>As I struggled to find any resources documenting the object-oriented aspect of the language, I felt compelled to write something for others without an OCaml background.</p><p>Now, my goal in writing this isn’t to push object-oriented programming. Instead, it is to highlight some of the features that the object support provides. For me, I find the real benefit is structural subtyping (row polymorphism), which I have been able to utilise to write pure functional code using the RIO Monad.</p><h3 id="an-introduction-to-objects-in-reason">An Introduction to Objects in Reason</h3><p>ReasonML is typically demonstrated as a functional language alongside Reason-React. In such tutorials you will often see records, but never objects, which seem to be a little discussed feature of the language.</p><p>Unlike Records, Objects are able to mutate their own state. Whilst it is possible to have a mutable field or reference on a record, it is not possible for a record to contain a method that mutates that state (it would have to be a function declared elsewhere).</p><p>Let’s demonstrate how an object can mutate its own state using a simple type for a cat, with an immutable name and a mutable age. This example reminds me of the sort of code I to write 10 years ago in Java… there are getters for both fields, but a setter for the age. Note the <code>.</code> after the brace, which indicates that this is an <em>object</em> and not a <em>record.</em></p><figure class="kg-card kg-code-card"><pre><code class="language-reason">type cat = {
  .
  getName: string,
  getAge: int,
  setAge: int =&gt; unit,
  describe: string
};</code></pre><figcaption>Unfortunately, Prism.js doesn't highlight objects very well!</figcaption></figure><p>Now lets see one way to implement that type:</p><pre><code class="language-reason">let makeCat: (string, int) =&gt; cat = (name, age) =&gt; {
  as self; // this is a reference to the object itself
  val mutable catAge = age;
  pub getName = name;
  pub getAge = catAge;
  pub setAge = age =&gt; catAge = age;
  pri ageString = string_of_int(catAge);
  pub describe = self#getName ++ " is " ++ self#ageString ++ " years old."
};</code></pre><p><br>There’s a few things to take from this.</p><p><code>as self;</code> This is a reference to the object itself and you can call it whatever you wish (even <code>_</code> if you don’t require it). You can think of this like <code>self</code> in Python or <code>this</code> in Java or TypeScript.</p><p><code>val mutable catAge = age</code> Here we define an mutable instance variable to hold the cat’s age. We don’t need to do this for <code>name</code> as it’s immutable. This can only be accessed using the public <code>getAge</code> method.</p><p><code>pub getAge = catAge</code> This is a method for fetching the age. As it is prefixed with <code>pub</code> the method is public. Note that it refers to the mutable reference and not the immutable <code>age</code> value we use to construct the instance.</p><p><code>pri ageString</code> On the other hand, this is a private method which cannot be called outside of the object definition.</p><p><code>pub describe = self#getName ++ " " ++ self#ageString ++ "years old";</code> Note that unlike with values and variables, you must use the <code>self</code> reference to call the other methods on the object. The <code>#</code> syntax is a little strange compared to the dot notation used by records.</p><p>Finally, an object does not require a type definition. You can define an object with no type and use it within a function. If you so wish you can delay defining the object until you need it.</p><pre><code class="language-reason">let double = x =&gt; x#value * 2;

let myObject = {
  as _;
  pub value = 3;
};

let result = double(myObject); // 6</code></pre><h3 id="using-classes-to-construct-objects">Using Classes to Construct Objects</h3><p>Whilst I used a function to build my object, you can use a class instead. The code is very similar:</p><pre><code class="language-reason">class cat(name, age) = {
  as self;
  val mutable age = age;

  pub getName = name;
  pub getAge = age;
  pub setAge = (newAge: int) =&gt; age = newAge;
  pri ageString = string_of_int(age);
  pub describe = name ++ " is " ++ self#ageString ++ " years old."
};</code></pre><h3 id="calling-methods-on-objects">Calling Methods on Objects</h3><p>Once you’ve constructed an object you can call it’s methods using the <code>#</code> syntax. The simple example below demonstrates that we are mutating the state of the cat object:</p><pre><code class="language-reason">let myOtherCat = new cat("Top Cat", 4);

myOtherCat#setAge(6)
myOtherCat#getAge // 6
myOtherCat.describe // "Top Cat is 6 years old."</code></pre><p>Apart from the strange syntax, the basics of objects and classes are rather simple. Whilst you could use these techniques to do build object-oriented systems in ReasonML, it's not common to do so – nor is it common in OCaml. Modules are recommended for most use cases, whilst objects are only used when polymorphism and inheritance are required. This article has only scratched the surface of what is possible with objects and I will expand upon in this in later posts.</p><p>Next up, <a href="http://itazura.io/objects-in-reasonml-part-2-inheritance/">implementing inheritance and virtual types.</a></p>]]></content:encoded></item><item><title><![CDATA[Automatic Swagger documentation for Dropwizard using Maven]]></title><description><![CDATA[<p><em>Preface: this is a <a href="https://itazuramono.com/2015/12/07/automatic-swagger-documentation-for-dropwizard-using-maven/">rather old article from my old blog</a>, just updated with code blocks and highlighting that Wordpress did not have at the time. I expect that the configuration has changed since and there may be libraries and tools that automate this process. </em></p><p>A few projects I have</p>]]></description><link>http://itazura.io:80/automatic-swagger-integration-for-dropwizard-using-maven/</link><guid isPermaLink="false">5e2837bf9eeb6d42b866de34</guid><category><![CDATA[java]]></category><dc:creator><![CDATA[RawToast]]></dc:creator><pubDate>Mon, 07 Dec 2015 11:51:00 GMT</pubDate><content:encoded><![CDATA[<p><em>Preface: this is a <a href="https://itazuramono.com/2015/12/07/automatic-swagger-documentation-for-dropwizard-using-maven/">rather old article from my old blog</a>, just updated with code blocks and highlighting that Wordpress did not have at the time. I expect that the configuration has changed since and there may be libraries and tools that automate this process. </em></p><p>A few projects I have worked on have looked at using <a href="http://swagger.io/">Swagger</a> to document the APIs. Unfortunately, the recommended way to achieve this involves adding a number of annotations to the endpoints and JSON representations which I feel clutter the codebase. I have never been happy with this, as in my opinion it is simply shifting the work from a wiki to some annoitations and is liable to the same problem — developers forget to update the annotations/documentation.</p><p>Hence I was very happy to find and implement automatic documentation using the <a href="https://github.com/teamcarma/swagger-jaxrs-doclet">Swagger JaxRs maven build plugin</a>. Configuring the plugin can be done in three simple steps. Just note that I am using swagger 2.1.0, and you probably should use the latest version.</p><ol><li>Add the plugin to your maven build (there are instructions for gradle).</li><li>Add the assets in your dropwizard application.</li><li>Import the swagger-ui files to into your project and amend a single line to point at your service definition.</li></ol><h3 id="integrating-the-plugin">Integrating the Plugin</h3><p>So the first job you need to do is add the following to your maven pom’s build section. Obviously you need to remove the “build” and “plugins” sections if you already have them in your pom.</p><pre><code class="language-xml">&lt;build&gt;
  &lt;plugins&gt;
  &lt;!-- Swagger Doclet --&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt;
      &lt;version&gt;2.9.1&lt;/version&gt;
      &lt;executions&gt;
          &lt;execution&gt;
          &lt;id&gt;generate-service-docs&lt;/id&gt;
          &lt;phase&gt;generate-resources&lt;/phase&gt;
          &lt;configuration&gt;
            &lt;doclet&gt;com.carma.swagger.doclet.ServiceDoclet&lt;/doclet&gt;
            &lt;docletArtifact&gt;
              &lt;groupId&gt;com.carma&lt;/groupId&gt;
              &lt;artifactId&gt;swagger-doclet&lt;/artifactId&gt;
              &lt;version&gt;1.1.1&lt;/version&gt;
            &lt;/docletArtifact&gt;
            &lt;reportOutputDirectory&gt;${project.build.outputDirectory}&lt;/reportOutputDirectory&gt;
            &lt;useStandardDocletOptions&gt;false&lt;/useStandardDocletOptions&gt;
            &lt;additionalparam&gt;-apiVersion 1 -docBasePath /apidocs -apiBasePath / -swaggerUiPath ../../../src/main/resources/swagger-ui-2.1.0&lt;/additionalparam&gt;
          &lt;/configuration&gt;
          &lt;goals&gt;
            &lt;goal&gt;javadoc&lt;/goal&gt;
          &lt;/goals&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
    &lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;</code></pre><p>Just take note of the following part:</p><pre><code class="language-xml">&lt;additionalparam&gt;-apiVersion 1 -docBasePath /apidocs -apiBasePath / -swaggerUiPath ../../../src/main/resources/swagger-ui-2.1.3&lt;/additionalparam&gt;</code></pre><ul><li><code>/apidocs</code> is the location of the documention resource.</li><li><code>../../../src/main/resources/swagger-ui-2.1.0</code> — is the location of swagger-ui. I have it pointing to the standard resources directory, as that’s where I will place swagger-ui.</li></ul><h3 id="register-the-assert-bundle">Register the Assert Bundle</h3><p>First double check you are already importing dropwizard-assets in your dependencies. It should look something like this:</p><pre><code class="language-xml">&lt;dependency&gt;
  &lt;groupId&gt;io.dropwizard&lt;/groupId&gt;
  &lt;artifactId&gt;dropwizard-assets&lt;/artifactId&gt;
  &lt;version&gt;${dropwizard.version}&lt;/version&gt;
&lt;/dependency&gt;</code></pre><p>Now you can add the assets bundle within your main application class. All you need to do is add the bundle in the initialize method of your main application, like so:</p><pre><code class="language-java">@Override
public void initialize(Bootstrap bootstrap) {
  // Other init code
  bootstrap.addBundle(
    new AssetsBundle("/apidocs", "/apidocs", "index.html")
  );
}</code></pre><p>Things to note here:</p><ul><li><code>/apidocs</code> is the location of the documentation endpoint. This is the same as the value in the <em><em>additionalparams</em></em> section of the maven plugin.</li><li><code>index.html</code> You shouldn’t need to change this. This is the html file that loads when you hit the resource and is provided by swagger-ui.</li></ul><h3 id="importing-the-swagger-ui-resources">Importing the Swagger UI Resources</h3><p>Download the latest version of Swagger (I’ve tested this setup against 2.1.0 and 2.1.3) from the <a href="https://github.com/swagger-api/swagger-ui/releases">Swagger-UI GitHub. </a>You’re only interested in the dist folder, so extract the zip to a temporary directory and delete everything except for the dist folder.</p><p>In the dist folder you need to open index.html to amend the swagger service definition location. By default swagger will be pointing to the ‘petstore example’, which isn’t very useful for us! This should be located on line 36 and will look like this:</p><pre><code>url = "http://petstore.swagger.io/v2/swagger.json";
</code></pre><p>Amend this to service.json and it will be pointing at the json schema generated by the plugin.</p><pre><code>url = "service.json";</code></pre><p>The next step is very simple. Create a folder in resources named <em><em>swagger-ui-&lt;version&gt;</em></em> so in my case: <code>src/main/resources/swagger-2.1.0</code> Now simply move the contents of the dist folder into this newly created directory.</p><h3 id="wrapping-it-up">Wrapping it up</h3><p>Now everything should be completed. Simply build your maven project (mvn clean package) and start your application as usual. The documentation should be located at <code>&lt;your application&gt;/apidocs/</code>. So if you were using the default Dropwizard ports try: <code>localhost:8080/apidocs/</code>  (Note the final slash is <strong><strong>important!</strong></strong>)</p>]]></content:encoded></item></channel></rss>