Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/deno.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ jobs:
with:
deno-version: ${{ matrix.deno }}
- run: deno --version
- run: deno test --allow-net --allow-env test/deno/*.js
- run: deno install && deno test --allow-net --allow-env test/deno/*.js
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,35 @@ app.get('/', async (req) => {
await app.listen({ port })
```

#### Fresh 2.x

```js
import i18next from 'https://deno.land/x/i18next/index.js'
import i18nextMiddleware from 'https://deno.land/x/i18next_http_middleware/index.js'
import { App, createDefine } from "jsr:@fresh/core";

i18next
.use(i18nextMiddleware.LanguageDetector)
.init({
preload: ["en", "fr"],
fallbackLng: "en",
resources: {
en: {
translation: { hi: "hello" }
},
fr: {
translation: { hi: "bonjour" }
}
}
});

const app = new App()
.use(i18nextMiddleware.freshPlugin(i18next))
.get("/", (ctx) => {
return new Response(ctx.state.t('hi'))
});
```

## add routes

```js
Expand Down
11 changes: 11 additions & 0 deletions lib/httpFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export const getQuery = (req) => {
if (req.url && req.url.searchParams) return req.url.searchParams
const url = req.url || (req.raw && req.raw.url)
if (url && url.indexOf('?') < 0) return {}
if (typeof URL !== 'undefined') {
try {
return Object.fromEntries(new URL(url).searchParams.entries())
} catch { }
}
console.log('no possibility found to get query')
return {}
}
Expand Down Expand Up @@ -120,6 +125,12 @@ export const setStatus = (res, code) => {
export const send = (res, body) => {
if (typeof res.send === 'function') return res.send(body)
if (res.request && res.response && res.app) res.body = body
if (typeof Response !== 'undefined' && res.constructor === Response) {
return new Response(body, {
status: res.status,
headers: res.headers
})
}
return body
}
export const getSession = (req) => {
Expand Down
36 changes: 36 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ const checkForCombinedReqRes = (req, res, next) => {
} else if (req.respond) {
res = req
if (!next) next = () => {}
} else if (typeof Request !== 'undefined' &&
typeof Response !== 'undefined' &&
req.req &&
req.req.constructor === Request
) {
if (req.state) {
req.state.res = req.state.res || new Response()
res = req.state.res
} else {
res = new Response()
}
req = req.req
if (!next) next = () => {}
}
} else if (!next && typeof res === 'function' && req.req && req.res) {
return {
Expand Down Expand Up @@ -137,6 +150,23 @@ export function koaPlugin (i18next, options) {
}
}

export function freshPlugin (i18next) {
return async (ctx) => {
handle(i18next, { attachLocals: true })(ctx)
ctx.state.t = ctx.req.t
ctx.state.i18n = ctx.req.i18n
ctx.state.lng = ctx.req.lng
ctx.state.locale = ctx.req.locale
ctx.state.language = ctx.req.language
ctx.state.languages = ctx.req.languages
const placeholder = ctx.state.res
delete ctx.state.res
const resp = await ctx.next()
resp.headers.set('Content-Language', placeholder.headers.get('Content-Language'))
return resp
}
}

export const hapiPlugin = {
name: 'i18next-http-middleware',
version: '1',
Expand Down Expand Up @@ -232,6 +262,11 @@ export function getResourcesHandler (i18next, options = {}) {
})
})

if (typeof Response !== 'undefined' &&
res.constructor === Response &&
typeof JSON !== 'undefined') {
return options.send(res, JSON.stringify(resources))
}
return options.send(res, resources)
}
}
Expand Down Expand Up @@ -311,6 +346,7 @@ export default {
plugin,
hapiPlugin,
koaPlugin,
freshPlugin,
handle,
getResourcesHandler,
missingKeyHandler,
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
"@babel/core": "7.26.0",
"@babel/preset-env": "7.26.0",
"@hapi/hapi": "^21.3.12",
"@opentelemetry/api": "^1.9.0",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are all these new dependencies necessary?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fresh2 core relies by default on these dependencies. This is the minimal set that enables loading the fresh2 App class in the tests

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but you added fresh for Deno... so there should not be any dependency in the package.json...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh I see....

"@preact/signals": "^2.2.1",
"@types/express-serve-static-core": "^5.0.1",
"@koa/router": "12.0.1",
"koa": "2.16.1",
Expand All @@ -48,6 +50,8 @@
"fastify": "5.3.2",
"i18next": "25.5.2",
"mocha": "10.8.2",
"preact": "10.27.2",
"preact-render-to-string": "6.6.3",
"supertest": "7.0.0",
"tsd": "0.31.2",
"uglify-js": "3.19.3"
Expand Down
33 changes: 33 additions & 0 deletions test/deno/addRoute.fresh.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from 'jsr:@std/expect'
import i18next from 'https://deno.land/x/i18next/index.js'
import i18nextMiddleware from '../../index.js'
const { test } = Deno
import { App } from "jsr:@fresh/core";

i18next
.init({
preload: ["en", "fr"],
fallbackLng: "en"
});

test('addRoute fresh', async () => {
const routeHandle = (ctx) => {
expect(ctx.state.lng).toEqual('en')
expect(ctx.state.locale).toEqual('en')
expect(ctx.state.language).toEqual('en')
expect(ctx.state.languages).toEqual( ['en'])
expect(ctx.state.i18n).not.toBeUndefined()
expect(ctx.state.t).not.toBeUndefined()

expect(ctx.state.t('key')).toEqual('key')
return new Response(ctx.state.t('key'))
}
const app = new App()
.use(i18nextMiddleware.freshPlugin(i18next))
i18nextMiddleware.addRoute(i18next, '/myroute/:lng/:ns', ['en'], app, 'get', routeHandle)
const handler = app.handler()
const res = await handler(
new Request('http://localhost/myroute/en/test')
);
expect(await res.text()).toEqual('key')
})
33 changes: 33 additions & 0 deletions test/deno/getResourcesHandler.fresh.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from 'jsr:@std/expect'
import i18next from 'https://deno.land/x/i18next/index.js'
import i18nextMiddleware from '../../index.js'
const { test } = Deno
import { App } from "jsr:@fresh/core";

i18next
.init({
preload: ["en", "fr"],
fallbackLng: "en",
saveMissing: true,
resources: {
en: {
translation: { hi: 'there' }
}
}
});

test('getResourcesHandler fresh', async () => {
const app = new App()
.use(i18nextMiddleware.freshPlugin(i18next))
.get('/', i18nextMiddleware.getResourcesHandler(i18next))
const handler = app.handler()
const res = await handler(
new Request('http://localhost?lng=en&ns=translation')
);
expect(res.status).toEqual(200)
expect(await res.json()).toEqual({
en: {
translation: { hi: 'there' }
}
})
})
39 changes: 39 additions & 0 deletions test/deno/middleware.fresh.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { expect } from 'jsr:@std/expect'
import i18next from 'https://deno.land/x/i18next/index.js'
import i18nextMiddleware from '../../index.js'
const { test } = Deno
import { App } from "jsr:@fresh/core";

i18next
.use(i18nextMiddleware.LanguageDetector)
.init({
preload: ["en", "fr"],
fallbackLng: "en",
resources: {
en: {
translation: { hi: "hello" }
},
fr: {
translation: { hi: "bonjour" }
}
}
});

test('middleware fresh', async () => {
const handler = new App()
.use(i18nextMiddleware.freshPlugin(i18next))
.get("/", (ctx) => {
return new Response(ctx.state.t('hi'))
})
.handler();

const headers = new Headers()
headers.append('Accept-Language', 'fr')
const res = await handler(
new Request('http://localhost',
{ headers }
));
const resHeaders = Object.fromEntries(res.headers.entries())
expect(resHeaders).toEqual(expect.objectContaining({ 'content-language': 'fr'}))
expect(await res.text()).toEqual("bonjour")
})