Skip to content

Commit

Permalink
fix send to support binary data and upgrade eta example to 3
Browse files Browse the repository at this point in the history
  • Loading branch information
v1rtl committed Jun 24, 2023
1 parent f9b8513 commit 1b23657
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 83 deletions.
21 changes: 15 additions & 6 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export { escapeHtml } from 'https://deno.land/x/escape_html@1.0.0/mod.ts'
export * as base64 from 'https://deno.land/std@0.185.0/encoding/base64.ts'
export { parseMediaType } from 'https://deno.land/std@0.185.0/media_types/parse_media_type.ts'
export * as mediaTyper from 'https://deno.land/x/media_typer@1.0.1/mod.ts'
export { contentDisposition } from 'https://esm.sh/@tinyhttp/content-disposition@2.0.9'
export { contentDisposition } from 'https://cdn.skypack.dev/@tinyhttp/content-disposition@2.0.9'
export { basename, extname } from 'https://deno.land/std@0.185.0/path/mod.ts'
export {
accepts,
Expand Down
34 changes: 12 additions & 22 deletions examples/eta/mod.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
import { renderFileAsync } from 'https://deno.land/x/eta@v2.0.1/mod.ts'
import type { EtaConfig } from 'https://deno.land/x/eta@v2.0.1/config.ts'
import { Eta } from 'https://deno.land/x/eta@v3.0.3/src/index.ts'
import type { EtaConfig } from 'https://deno.land/x/eta@v3.0.3/src/config.ts'
import { App } from '../../mod.ts'
import { path } from '../../deps.ts'

const eta = new Eta({
views: path.join(Deno.cwd(), 'views'),
})
const app = new App<EtaConfig>()

app.engine('eta', renderFileAsync)

function func() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('HI FROM ASYNC')
}, 20)
})
}

app.use(
async (_, res) => {
await res.render(
'index.eta',
{ name: 'Eta', func },
{
renderOptions: {
async: true,
cache: true,
},
},
(_, res) => {
res.end(
eta.render(
'index',
{ name: 'Eta' },
),
)
},
)
Expand Down
4 changes: 1 addition & 3 deletions examples/eta/views/index.eta
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
Hello from <%= it.name %>

Async func: <%= await it.func() %>
Hello from <%= it.name %>
2 changes: 1 addition & 1 deletion examples/https/mod.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { App } from '../../app.ts'
import { serveTls } from 'https://deno.land/std@0.185.0/http/server.ts'
import { serveTls } from 'https://deno.land/std@0.192.0/http/server.ts'

const app = new App()

Expand Down
74 changes: 37 additions & 37 deletions extensions/res/send/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,72 +3,72 @@ import { json } from './json.ts'
import { createETag, setCharset } from '../utils.ts'
import { end } from './end.ts'

const isBuffer = (body: unknown) =>
body instanceof Uint8Array || body instanceof Blob ||
body instanceof ArrayBuffer || body instanceof ReadableStream<Uint8Array>

export const send = <
Req extends Request & { fresh?: boolean } = Request & { fresh?: boolean },
Res extends DummyResponse = DummyResponse,
>(req: Req, res: Res) =>
async (body: unknown) => {
let bodyToSend = body

// in case of object - turn it to json
if (typeof bodyToSend === 'object' && bodyToSend !== null) {
if (isBuffer(body)) {
bodyToSend = body
} else if (typeof body === 'object' && body !== null) {
// in case of object - turn it to json
bodyToSend = JSON.stringify(body, null, 2)
res._init.headers?.set('Content-Type', 'application/json')
} else {
if (typeof bodyToSend === 'string') {
// reflect this in content-type
const type = res._init.headers?.get('Content-Type')
} else if (typeof body === 'string') {
// reflect this in content-type
const type = res._init.headers.get('Content-Type')

if (type && typeof type === 'string') {
res._init.headers?.set('Content-Type', setCharset(type))
} else {res._init.headers?.set(
'Content-Type',
setCharset('text/html'),
)}
}
if (type && typeof type === 'string') {
res._init.headers.set('Content-Type', setCharset(type))
} else {res._init.headers.set(
'Content-Type',
setCharset('text/html'),
)}
}

// populate ETag
let etag: string | undefined
if (
bodyToSend && !res._init.headers?.get('etag') &&
(etag = await createETag(bodyToSend as string))
typeof body === 'string' && !res._init.headers.get('etag')
) {
res._init.headers?.set('etag', etag)
etag = await createETag(bodyToSend as string)
}
{
if (etag) res._init.headers.set('etag', etag!)
}

// freshness
if (req.fresh) res._init.status = 304

// strip irrelevant headers
if (res._init.status === 204 || res._init.status === 304) {
res._init.headers?.delete('Content-Type')
res._init.headers?.delete('Content-Length')
res._init.headers?.delete('Transfer-Encoding')
res._init.headers.delete('Content-Type')
res._init.headers.delete('Content-Length')
res._init.headers.delete('Transfer-Encoding')
bodyToSend = ''
}

if (req.method === 'HEAD') {
return end(res)(bodyToSend as BodyInit)
}

if (typeof bodyToSend === 'object') {
if (typeof body === 'object') {
if (body == null) {
return end(res)('')
} else if (
bodyToSend instanceof Uint8Array || bodyToSend instanceof File
) {
if (!res._init.headers?.get('Content-Type')) {
return end(res)(null)
} else if (isBuffer(body)) {
if (!res._init.headers.get('Content-Type')) {
res._init.headers.set('content-type', 'application/octet-stream')
}

return end(res)(bodyToSend)
} else {
return json(res)(bodyToSend)
}
} else {
if (typeof bodyToSend !== 'string') {
bodyToSend = (bodyToSend as string).toString()
}

return end(res)(bodyToSend as BodyInit)
return end(res)(bodyToSend as BodyInit)
} else return json(res)(bodyToSend)
}
if (typeof bodyToSend !== 'string') {
bodyToSend = (bodyToSend as string).toString()
}
return end(res)(bodyToSend as string)
}
25 changes: 14 additions & 11 deletions tests/modules/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { json, send, sendStatus, status } from '../../extensions/res/mod.ts'
import { runServer } from '../util.test.ts'
import { App } from '../../mod.ts'

const te = new TextEncoder()

describe('json(body)', () => {
it('should send a JSON reply when an object is passed', async () => {
const app = runServer((_, res) => {
Expand Down Expand Up @@ -118,17 +120,18 @@ describe('send(body)', () => {
.expectHeader('Content-Type', null)
.expectHeader('Transfer-Encoding', null)
})
// it('should set Content-Type to application/octet-stream for buffers if the header hasn\'t been set before', async () => {
// const app = runServer((req, res) =>
// send(req, res)(Buffer.from('Hello World', 'utf-8')).end()
// )

// const res = await makeFetch(app)('/')
// res.expectHeader(
// 'Content-Type',
// 'application/octet-stream',
// )
// })
it('should set Content-Type to application/octet-stream for buffers if the header hasn\'t been set before', async () => {
const app = runServer(async (req, res) => {
const r = await send(req, res)(te.encode('Hello World'))
return new Response(r._body, r._init)
})

const res = await makeFetch(app)('/')
res.expectHeader(
'Content-Type',
'application/octet-stream',
)
})
it('should set 304 status for fresh requests', async () => {
const etag = 'abc'

Expand Down
2 changes: 1 addition & 1 deletion tests/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { THRequest } from '../request.ts'
import type { DummyResponse, THResponse } from '../response.ts'
import type { AppConstructor, Handler } from '../types.ts'
import { makeFetch } from '../dev_deps.ts'
import { ConnInfo } from 'https://deno.land/x/superfetch@1.0.4/types.ts'
import type { ConnInfo } from 'https://deno.land/x/superfetch@1.0.5/types.ts'
export const supertest = (app: App) => {
const fetch = makeFetch((req, conn) => app.handler(req, conn))

Expand Down
2 changes: 1 addition & 1 deletion types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ type TemplateFunc<O> = (
path: string,
locals: Record<string, unknown>,
opts: TemplateEngineOptions<O>,
) => Promise<string>
) => string | Promise<string>

export interface ConnInfo {
/** The local address of the connection. */
Expand Down

0 comments on commit 1b23657

Please sign in to comment.