0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-03 17:34:47 -05:00

refactor: use serde ops more (#9817)

This commit is contained in:
crowlKats 2021-03-17 22:33:29 +01:00 committed by GitHub
parent bd961c3bc3
commit b3fe85163f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 76 additions and 97 deletions

View file

@ -9,7 +9,6 @@ use deno_core::error::AnyError;
use deno_core::futures::Future; use deno_core::futures::Future;
use deno_core::futures::Stream; use deno_core::futures::Stream;
use deno_core::futures::StreamExt; use deno_core::futures::StreamExt;
use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::url::Url; use deno_core::url::Url;
@ -103,27 +102,25 @@ pub fn get_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_fetch.d.ts") PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_fetch.d.ts")
} }
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchArgs {
method: Option<String>,
url: String,
base_url: Option<String>,
headers: Vec<(String, String)>,
client_rid: Option<u32>,
has_body: bool,
}
pub fn op_fetch<FP>( pub fn op_fetch<FP>(
state: &mut OpState, state: &mut OpState,
args: Value, args: FetchArgs,
data: &mut [ZeroCopyBuf], data: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> ) -> Result<Value, AnyError>
where where
FP: FetchPermissions + 'static, FP: FetchPermissions + 'static,
{ {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FetchArgs {
method: Option<String>,
url: String,
base_url: Option<String>,
headers: Vec<(String, String)>,
client_rid: Option<u32>,
has_body: bool,
}
let args: FetchArgs = serde_json::from_value(args)?;
let client = if let Some(rid) = args.client_rid { let client = if let Some(rid) = args.client_rid {
let r = state let r = state
.resource_table .resource_table
@ -203,19 +200,17 @@ where
})) }))
} }
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchSendArgs {
rid: u32,
}
pub async fn op_fetch_send( pub async fn op_fetch_send(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: FetchSendArgs,
_data: BufVec, _data: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Args {
rid: u32,
}
let args: Args = serde_json::from_value(args)?;
let request = state let request = state
.borrow_mut() .borrow_mut()
.resource_table .resource_table
@ -273,18 +268,17 @@ pub async fn op_fetch_send(
})) }))
} }
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchRequestWriteArgs {
rid: u32,
}
pub async fn op_fetch_request_write( pub async fn op_fetch_request_write(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: FetchRequestWriteArgs,
data: BufVec, data: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Args {
rid: u32,
}
let args: Args = serde_json::from_value(args)?;
let rid = args.rid; let rid = args.rid;
let buf = match data.len() { let buf = match data.len() {
@ -304,18 +298,17 @@ pub async fn op_fetch_request_write(
Ok(json!({})) Ok(json!({}))
} }
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FetchResponseReadArgs {
rid: u32,
}
pub async fn op_fetch_response_read( pub async fn op_fetch_response_read(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: FetchResponseReadArgs,
data: BufVec, data: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Args {
rid: u32,
}
let args: Args = serde_json::from_value(args)?;
let rid = args.rid; let rid = args.rid;
if data.len() != 1 { if data.len() != 1 {
@ -385,24 +378,22 @@ impl HttpClientResource {
} }
} }
#[derive(Deserialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
pub struct CreateHttpClientOptions {
ca_file: Option<String>,
ca_data: Option<String>,
}
pub fn op_create_http_client<FP>( pub fn op_create_http_client<FP>(
state: &mut OpState, state: &mut OpState,
args: Value, args: CreateHttpClientOptions,
_zero_copy: &mut [ZeroCopyBuf], _zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> ) -> Result<Value, AnyError>
where where
FP: FetchPermissions + 'static, FP: FetchPermissions + 'static,
{ {
#[derive(Deserialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
struct CreateHttpClientOptions {
ca_file: Option<String>,
ca_data: Option<String>,
}
let args: CreateHttpClientOptions = serde_json::from_value(args)?;
if let Some(ca_file) = args.ca_file.clone() { if let Some(ca_file) = args.ca_file.clone() {
let permissions = state.borrow::<FP>(); let permissions = state.borrow::<FP>();
permissions.check_read(&PathBuf::from(ca_file))?; permissions.check_read(&PathBuf::from(ca_file))?;

View file

@ -4,7 +4,6 @@ use deno_core::error::generic_error;
use deno_core::error::type_error; use deno_core::error::type_error;
use deno_core::error::uri_error; use deno_core::error::uri_error;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::url::form_urlencoded; use deno_core::url::form_urlencoded;
@ -17,31 +16,31 @@ use serde::Serialize;
use std::panic::catch_unwind; use std::panic::catch_unwind;
use std::path::PathBuf; use std::path::PathBuf;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UrlParseArgs {
href: String,
base_href: Option<String>,
// If one of the following are present, this is a setter call. Apply the
// proper `Url::set_*()` method after (re)parsing `href`.
set_hash: Option<String>,
set_host: Option<String>,
set_hostname: Option<String>,
set_password: Option<String>,
set_pathname: Option<String>,
set_port: Option<String>,
set_protocol: Option<String>,
set_search: Option<String>,
set_username: Option<String>,
}
/// Parse `UrlParseArgs::href` with an optional `UrlParseArgs::base_href`, or an /// Parse `UrlParseArgs::href` with an optional `UrlParseArgs::base_href`, or an
/// optional part to "set" after parsing. Return `UrlParts`. /// optional part to "set" after parsing. Return `UrlParts`.
pub fn op_url_parse( pub fn op_url_parse(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: Value, args: UrlParseArgs,
_zero_copy: &mut [ZeroCopyBuf], _zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct UrlParseArgs {
href: String,
base_href: Option<String>,
// If one of the following are present, this is a setter call. Apply the
// proper `Url::set_*()` method after (re)parsing `href`.
set_hash: Option<String>,
set_host: Option<String>,
set_hostname: Option<String>,
set_password: Option<String>,
set_pathname: Option<String>,
set_port: Option<String>,
set_protocol: Option<String>,
set_search: Option<String>,
set_username: Option<String>,
}
let args: UrlParseArgs = serde_json::from_value(args)?;
let base_url = args let base_url = args
.base_href .base_href
.as_ref() .as_ref()
@ -120,11 +119,10 @@ pub fn op_url_parse(
pub fn op_url_parse_search_params( pub fn op_url_parse_search_params(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: Value, args: String,
_zero_copy: &mut [ZeroCopyBuf], _zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let search: String = serde_json::from_value(args)?; let search_params: Vec<_> = form_urlencoded::parse(args.as_bytes())
let search_params: Vec<_> = form_urlencoded::parse(search.as_bytes())
.into_iter() .into_iter()
.collect(); .collect();
Ok(json!(search_params)) Ok(json!(search_params))
@ -132,12 +130,11 @@ pub fn op_url_parse_search_params(
pub fn op_url_stringify_search_params( pub fn op_url_stringify_search_params(
_state: &mut deno_core::OpState, _state: &mut deno_core::OpState,
args: Value, args: Vec<(String, String)>,
_zero_copy: &mut [ZeroCopyBuf], _zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let search_params: Vec<(String, String)> = serde_json::from_value(args)?;
let search = form_urlencoded::Serializer::new(String::new()) let search = form_urlencoded::Serializer::new(String::new())
.extend_pairs(search_params) .extend_pairs(args)
.finish(); .finish();
Ok(json!(search)) Ok(json!(search))
} }

View file

@ -18,7 +18,7 @@ use deno_core::JsRuntime;
use deno_core::OpState; use deno_core::OpState;
use deno_core::RcRef; use deno_core::RcRef;
use deno_core::Resource; use deno_core::Resource;
use deno_core::{serde_json, ZeroCopyBuf}; use deno_core::ZeroCopyBuf;
use http::{Method, Request, Uri}; use http::{Method, Request, Uri};
use serde::Deserialize; use serde::Deserialize;
@ -83,7 +83,7 @@ impl WsStreamResource {}
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CheckPermissionArgs { pub struct CheckPermissionArgs {
url: String, url: String,
} }
@ -92,14 +92,12 @@ struct CheckPermissionArgs {
// but actual op that connects WS is async. // but actual op that connects WS is async.
pub fn op_ws_check_permission<WP>( pub fn op_ws_check_permission<WP>(
state: &mut OpState, state: &mut OpState,
args: Value, args: CheckPermissionArgs,
_zero_copy: &mut [ZeroCopyBuf], _zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, AnyError> ) -> Result<Value, AnyError>
where where
WP: WebSocketPermissions + 'static, WP: WebSocketPermissions + 'static,
{ {
let args: CheckPermissionArgs = serde_json::from_value(args)?;
state state
.borrow::<WP>() .borrow::<WP>()
.check_net_url(&url::Url::parse(&args.url)?)?; .check_net_url(&url::Url::parse(&args.url)?)?;
@ -109,21 +107,19 @@ where
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CreateArgs { pub struct CreateArgs {
url: String, url: String,
protocols: String, protocols: String,
} }
pub async fn op_ws_create<WP>( pub async fn op_ws_create<WP>(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: CreateArgs,
_bufs: BufVec, _bufs: BufVec,
) -> Result<Value, AnyError> ) -> Result<Value, AnyError>
where where
WP: WebSocketPermissions + 'static, WP: WebSocketPermissions + 'static,
{ {
let args: CreateArgs = serde_json::from_value(args)?;
{ {
let s = state.borrow(); let s = state.borrow();
s.borrow::<WP>() s.borrow::<WP>()
@ -217,7 +213,7 @@ where
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct SendArgs { pub struct SendArgs {
rid: u32, rid: u32,
kind: String, kind: String,
text: Option<String>, text: Option<String>,
@ -225,11 +221,9 @@ struct SendArgs {
pub async fn op_ws_send( pub async fn op_ws_send(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: SendArgs,
bufs: BufVec, bufs: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let args: SendArgs = serde_json::from_value(args)?;
let msg = match args.kind.as_str() { let msg = match args.kind.as_str() {
"text" => Message::Text(args.text.unwrap()), "text" => Message::Text(args.text.unwrap()),
"binary" => Message::Binary(bufs[0].to_vec()), "binary" => Message::Binary(bufs[0].to_vec()),
@ -250,7 +244,7 @@ pub async fn op_ws_send(
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct CloseArgs { pub struct CloseArgs {
rid: u32, rid: u32,
code: Option<u16>, code: Option<u16>,
reason: Option<String>, reason: Option<String>,
@ -258,10 +252,9 @@ struct CloseArgs {
pub async fn op_ws_close( pub async fn op_ws_close(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: CloseArgs,
_bufs: BufVec, _bufs: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let args: CloseArgs = serde_json::from_value(args)?;
let rid = args.rid; let rid = args.rid;
let msg = Message::Close(args.code.map(|c| CloseFrame { let msg = Message::Close(args.code.map(|c| CloseFrame {
code: CloseCode::from(c), code: CloseCode::from(c),
@ -283,17 +276,15 @@ pub async fn op_ws_close(
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct NextEventArgs { pub struct NextEventArgs {
rid: u32, rid: u32,
} }
pub async fn op_ws_next_event( pub async fn op_ws_next_event(
state: Rc<RefCell<OpState>>, state: Rc<RefCell<OpState>>,
args: Value, args: NextEventArgs,
_bufs: BufVec, _bufs: BufVec,
) -> Result<Value, AnyError> { ) -> Result<Value, AnyError> {
let args: NextEventArgs = serde_json::from_value(args)?;
let resource = state let resource = state
.borrow_mut() .borrow_mut()
.resource_table .resource_table