ExtensionsOutput Formatters

Output formatters

You may want to deliver a response in a specific file format like csv, as you can see in the index action from the CRUD abstraction extension.

Dreamer has optional built-in formatters for csv and xlsx. You can install and use them as needed. They come in two separate packages: @oniryk/dreamer-csv and @oniryk/dreamer-xls.

You can also create your own formatter. It must implement the following type:

type OutputFormatFn<M extends typeof BaseModel> = {
  (ctx: HttpContext, rows: InstanceType<M>[]): Promise<void> | void
  formatName: string
}

Let’s create a new example formatter:

export default function pdf({ name }: { name: string }) {
  const handler = async function ({ response }: HttpContext, rows: unknown[]) {
    const content = await convertToPdf(rows); // imaginary function
 
    response.header("Content-Type", "application/pdf");
    response.header("Content-Disposition", `attachment; filename="${name}"`);
    response.send(content);
  };
 
  handler.formatName = "pdf";
  return handler;
}

Using our new formatter:

export default class PostsController {
  public index = index(Post, {
    formats: [
      pdf({ name: 'posts.pdf' })
    ]
  })
}