From e89295b176b4f494d19b547b6b4d7c98d0cf1da1 Mon Sep 17 00:00:00 2001 From: Aaron O'Mullan Date: Thu, 29 Apr 2021 00:16:45 +0200 Subject: refactor(extensions): reintroduce builder (#10412) --- core/extensions.rs | 81 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 52 insertions(+), 29 deletions(-) (limited to 'core') diff --git a/core/extensions.rs b/core/extensions.rs index eb6f6f719..134aab5d4 100644 --- a/core/extensions.rs +++ b/core/extensions.rs @@ -15,38 +15,13 @@ pub struct Extension { initialized: bool, } -impl Extension { - pub fn new( - js_files: Option>, - ops: Option>, - opstate_fn: Option>, - middleware_fn: Option>, - ) -> Self { - Self { - js_files, - ops, - opstate_fn, - middleware_fn, - initialized: false, - } - } - - pub fn pure_js(js_files: Vec) -> Self { - Self::new(Some(js_files), None, None, None) - } - - pub fn with_ops( - js_files: Vec, - ops: Vec, - opstate_fn: Option>, - ) -> Self { - Self::new(Some(js_files), Some(ops), opstate_fn, None) - } -} - // Note: this used to be a trait, but we "downgraded" it to a single concrete type // for the initial iteration, it will likely become a trait in the future impl Extension { + pub fn builder() -> ExtensionBuilder { + Default::default() + } + /// returns JS source code to be loaded into the isolate (either at snapshotting, /// or at startup). as a vector of a tuple of the file name, and the source code. pub(crate) fn init_js(&self) -> Vec { @@ -81,6 +56,54 @@ impl Extension { } } +// Provides a convenient builder pattern to declare Extensions +#[derive(Default)] +pub struct ExtensionBuilder { + js: Vec, + ops: Vec, + state: Option>, + middleware: Option>, +} + +impl ExtensionBuilder { + pub fn js(&mut self, js_files: Vec) -> &mut Self { + self.js.extend(js_files); + self + } + + pub fn ops(&mut self, ops: Vec) -> &mut Self { + self.ops.extend(ops); + self + } + + pub fn state(&mut self, opstate_fn: F) -> &mut Self + where + F: Fn(&mut OpState) -> Result<(), AnyError> + 'static, + { + self.state = Some(Box::new(opstate_fn)); + self + } + + pub fn middleware(&mut self, middleware_fn: F) -> &mut Self + where + F: Fn(&'static str, Box) -> Box + 'static, + { + self.middleware = Some(Box::new(middleware_fn)); + self + } + + pub fn build(&mut self) -> Extension { + let js_files = Some(std::mem::take(&mut self.js)); + let ops = Some(std::mem::take(&mut self.ops)); + Extension { + js_files, + ops, + opstate_fn: self.state.take(), + middleware_fn: self.middleware.take(), + initialized: false, + } + } +} /// Helps embed JS files in an extension. Returns Vec<(&'static str, &'static str)> /// representing the filename and source code. /// -- cgit v1.2.3