-
Notifications
You must be signed in to change notification settings - Fork 343
feat: worker fetch example #411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for pointing out this gap in the examples.
#[event(fetch)] | ||
pub async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> { | ||
Router::new() | ||
.get_async("/pokemon/:name", handle_single) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we call this pokemon_route_handler
, get_pokemon
or something that makes it clearer the function is the route handler?
@@ -0,0 +1,21 @@ | |||
use worker::{event, Context, Env, Fetch, Request, Response, Result, RouteContext, Router, Url}; | |||
|
|||
const ENDPOINT: &str = "https://pokeapi.co/api/v2/pokemon"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Again, more descriptive would help:
const ENDPOINT: &str = "https://pokeapi.co/api/v2/pokemon"; | |
const POKEMON_API_URL: &str = "https://pokeapi.co/api/v2/pokemon"; |
async fn fetch_pokemon(url_string: &str) -> Result<Response> { | ||
// construct a new Url | ||
let url = Url::parse(url_string)?; | ||
Fetch::Url(url).send().await | ||
} | ||
|
||
async fn handle_single(_: Request, ctx: RouteContext<()>) -> Result<Response> { | ||
Ok(fetch_pokemon(&format!("{ENDPOINT}/{}", ctx.param("name").unwrap())).await?) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems like it would be easier to read and follow as a single function implementation.
Provides a simple example on using worker::Fetch to fetch external API in Cloudflare Workers