Skip to content

Commit

Permalink
chore: migrate examples to v2 (#897)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreyYolkin authored Dec 4, 2024
1 parent 7711f78 commit 5831a5b
Show file tree
Hide file tree
Showing 17 changed files with 90 additions and 149 deletions.
14 changes: 5 additions & 9 deletions examples/body.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import { createApp, createRouter, readJSONBody } from "h3";
import { createH3 } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
.get("/", () => "use GET method to try!")
app
.get("/", () => "Try sending a POST request with a body!")
.post("/", async (event) => {
const body = await readJSONBody(event);
// You can also use `readFormDataBody` to get a FormData object, `readMultiPartFormData` to get an array of MultiPartData or `readRawBody` to get a Buffer.
return {
body,
body: await event.request.text(),
};
});

app.use(router);
10 changes: 4 additions & 6 deletions examples/cookies.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createApp, createRouter, getCookie, setCookie } from "h3";
import { createH3, getCookie, setCookie } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
app
.get("/", (event) => {
const testCookie = getCookie(event, "testCookie");
return `testCookie is ${JSON.stringify(testCookie)} (go to /set to set it)`;
Expand All @@ -11,7 +11,5 @@ const router = createRouter()
// By default, path is set to `/`. You can use any of the options supported by the Set-Cookie header.
// @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
setCookie(event, "testCookie", "bar", { httpOnly: true });
return "testCookie is set";
return "TestCookie is set. Go back to / to see it!";
});

app.use(router);
17 changes: 5 additions & 12 deletions examples/cors.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import { createApp, createRouter, handleCors } from "h3";
import { createH3, handleCors } from "h3";

export const app = createApp();
export const app = createH3();

app.use((event) => {
if (
handleCors(event, {
origin: "*",
})
) {
app.get("/hello", (event) => {
if (handleCors(event, { origin: "*" })) {
return;
}
return "Hello World!";
});

const router = createRouter().get("/hello", () => "world");

app.use(router);
11 changes: 5 additions & 6 deletions examples/errors.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { createApp, createError, createRouter } from "h3";
import { createError, createH3 } from "h3";

export const app = createApp({ debug: true });
export const app = createH3({ debug: true });

const router = createRouter()
app
.get("/", () => {
// Always "throw" errors to propagate them to the error handler
throw createError({ statusMessage: "Simple error!", statusCode: 301 });
})
.get("/complexe-error", () => {
.get("/complex-error", () => {
console.log("complex-error");
// You can fully customize errors by adding data, cause and if it's a fatal error or not
throw createError({
status: 400,
Expand All @@ -24,5 +25,3 @@ const router = createRouter()
data: { foo: "bar" },
});
});

app.use(router);
4 changes: 2 additions & 2 deletions examples/first-server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createApp } from "h3";
import { createH3 } from "h3";

export const app = createApp();
export const app = createH3();

app
// `/` is the root path and will response to every request.
Expand Down
22 changes: 7 additions & 15 deletions examples/handler-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
import {
createApp,
createRouter,
defineEventHandler,
defineRequestMiddleware,
defineResponseMiddleware,
} from "h3";
import { createH3, defineEventHandler } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter().get(
app.get(
"/",
defineEventHandler({
onRequest: defineRequestMiddleware(() => {
onRequest: () => {
// Do anything you want here like authentication, rate limiting, etc.
console.log("onRequest");
// Never return anything from onRequest to avoid to close the connection
}),
onBeforeResponse: defineResponseMiddleware(() => {
},
onBeforeResponse: () => {
// Do anything you want here like logging, collecting metrics, or output compression, etc.
console.log("onResponse");
// Never return anything from onResponse to avoid to close the connection
}),
},
handler: () => "GET: hello world",
}),
);

app.use(router);
32 changes: 8 additions & 24 deletions examples/headers.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,15 @@
import {
createApp,
createRouter,
getRequestHeader,
getResponseHeaders,
setResponseHeader,
} from "h3";
import { createH3 } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter().get("/user-agent", (event) => {
const userAgent = getRequestHeader(event, "user-agent");
// You can also use `getRequestHeaders` to get all headers at once.
// const headers = getRequestHeaders(event)
app.get("/user-agent", (event) => {
const userAgent = event.headers.get("user-agent");

setResponseHeader(event, "content-type", "text/plain");
setResponseHeader(event, "x-server", "nitro");
// You can also use `setResponseHeaders` to set multiple headers at once.
// setResponseHeaders(event, { 'x-server': 'nitro', 'content-type': 'text/plain' })

const responseHeaders = getResponseHeaders(event);
// You can also use `getResponseHeader` to get a single header.
// const contentType = getResponseHeader(event, 'content-type')
event.response.setHeader("content-type", "text/plain");
event.response.setHeader("x-server", "nitro");

return {
userAgent,
responseHeaders,
userAgent: userAgent,
responseHeaders: Object.fromEntries(event.response.headers.entries()),
};
});

app.use(router);
13 changes: 6 additions & 7 deletions examples/nested-router.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { createApp, createRouter, useBase, redirect } from "h3";
import { createH3, redirect, withBase } from "h3";

// Init App
export const app = createApp({ debug: true });
export const app = createH3({ debug: true });

// Main Router
const router = createRouter();
router.use("/", (event) => redirect(event, "/api/test"));
app.use(router);
app.use("/", (event) => redirect(event, "/api/test"));

const apiRouter = createH3();

// Nested API Router
const apiRouter = createRouter();
router.use("/api/**", useBase("/api", apiRouter.handler));
app.use("/api/**", withBase("/api", apiRouter.handler));
apiRouter.use("/test", () => "API /test");
11 changes: 4 additions & 7 deletions examples/query-params.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { createApp, createRouter, getQuery } from "h3";
import { createH3 } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter().get("/", (event) => {
const query = getQuery(event);
return `Hello ${query.name}`;
app.get("/", (event) => {
return `Hello ${event.query.get("name") || "anonymous"}!`;
});

app.use(router);
8 changes: 3 additions & 5 deletions examples/redirect.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { createApp, createRouter, redirect } from "h3";
import { createH3, redirect } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
app
.get("/unjs", (event) => {
return redirect(event, "https://unjs.io/packages/h3"); // 302 Found by default
})
.get("/permanent", (event) => {
// You can use any 3xx status code you want
return redirect(event, "https://unjs.io/packages/h3", 301);
});

app.use(router);
8 changes: 3 additions & 5 deletions examples/router.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { createApp, createRouter } from "h3";
import { createH3 } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
app
.get("/", () => "GET: hello world")
.post("/", () => "POST: hello world")
.put("/", () => "PUT: hello world")
.delete("/", () => "DELETE: hello world")
.patch("/", () => "PATCH: hello world")
.head("/", () => "HEAD: hello world");

app.use(router);
34 changes: 14 additions & 20 deletions examples/server-sent-events.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import { createApp, createRouter, eventHandler, createEventStream } from "h3";
import { createH3, createEventStream } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter();
app.use(router);
app.get("/", (event) => {
const eventStream = createEventStream(event);

router.get(
"/",
eventHandler((event) => {
const eventStream = createEventStream(event);
// Send a message every second
const interval = setInterval(async () => {
await eventStream.push("Hello world");
}, 1000);

// Send a message every second
const interval = setInterval(async () => {
await eventStream.push("Hello world");
}, 1000);
// cleanup the interval when the connection is terminated or the writer is closed
eventStream.onClosed(() => {
clearInterval(interval);
});

// cleanup the interval when the connection is terminated or the writer is closed
eventStream.onClosed(() => {
clearInterval(interval);
});

return eventStream.send();
}),
);
return eventStream.send();
});
25 changes: 8 additions & 17 deletions examples/status.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
import {
createApp,
createRouter,
getResponseStatus,
getResponseStatusText,
noContent,
setResponseStatus,
} from "h3";
import { createH3, noContent } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
app
.get("/not-found", (event) => {
setResponseStatus(event, 404);
event.response.status = 404;

return "Not found"; // You need to explicitly return something to avoid a 404 'Cannot find any path matching "/not-found"' response.
})
.get("/bad-request", (event) => {
setResponseStatus(event, 400, "Bad request message"); // You can customize the status message.
const status = 400;
const text = "Bad request message";

const status = getResponseStatus(event); // You can get the status message.
const text = getResponseStatusText(event); // You can get the status message.
event.response.status = status;
event.response.statusText = text; // You can customize the status message.

return {
status,
text,
};
})
.get("/no-content", (event) => {
// Do not need to explicitly return because `noContent` will cut the connection.
return noContent(event);
});

app.use(router);
8 changes: 3 additions & 5 deletions examples/url-params.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createApp, createRouter, getRouterParam, getRouterParams } from "h3";
import { createH3, getRouterParam, getRouterParams } from "h3";

export const app = createApp();
export const app = createH3();

const router = createRouter()
app
.get("/:name", (event) => {
const name = getRouterParam(event, "name");
return `Hello ${name}`;
Expand All @@ -12,5 +12,3 @@ const router = createRouter()

return `Hello ${params.name}, you are ${params.age} years old`;
});

app.use(router);
4 changes: 2 additions & 2 deletions examples/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createApp, defineWebSocketHandler } from "h3";
import { createH3, defineWebSocketHandler } from "h3";

export const app = createApp();
export const app = createH3();

app.use(() =>
fetch(
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
"rou3": "^0.5.1",
"uncrypto": "^0.1.3"
},
"resolutions": {
"h3": "link:."
},
"devDependencies": {
"@types/connect": "^3.4.38",
"@types/express": "^5.0.0",
Expand Down
Loading

0 comments on commit 5831a5b

Please sign in to comment.