Compare commits

..

2 Commits

Author SHA1 Message Date
ato
a634528d02 feat: create an async fs lua module
All checks were successful
continuous-integration/drone/push Build is passing
2023-02-16 19:04:50 +01:00
ato
83527a7f59 fix: correct return from lua res 2023-02-16 19:03:55 +01:00
6 changed files with 52 additions and 24 deletions

View File

@ -1,11 +1,12 @@
local app = create_app()
app:post("/", function(req,res)
for k,v in pairs(req.parts) do
print("name", k)
print("filename", v.filename)
print("content", v.content)
if req.parts.myfile == nil then
res.status = 400
res.body = "Missing myfile field"
return res
end
fs:write("yololo.txt", req.parts.myfile.content)
return res
end)

View File

@ -1,14 +0,0 @@
use mlua::Lua;
use std::time::Duration;
use tokio::time::sleep;
pub fn load_builtins(lua: &Lua) {
let sleep = lua
.create_async_function(|_l, n: u64| async move {
sleep(Duration::from_secs(n)).await;
Ok(())
})
.unwrap();
lua.globals().set("sleep", sleep).unwrap();
}

16
src/api/fs.rs Normal file
View File

@ -0,0 +1,16 @@
use mlua::UserData;
#[derive(Clone)]
pub struct FS {}
impl UserData for FS {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_method(
"write",
|_l, _this, (filename, contents): (String, String)| async move {
tokio::fs::write(filename, contents).await.unwrap();
Ok(())
},
)
}
}

View File

@ -1 +1,22 @@
pub mod builtins;
pub mod fs;
use mlua::Lua;
use std::time::Duration;
use tokio::time::sleep;
use self::fs::FS;
pub fn load_builtins(lua: &Lua) {
let sleep = lua
.create_async_function(|_l, n: u64| async move {
sleep(Duration::from_secs(n)).await;
Ok(())
})
.unwrap();
lua.globals().set("sleep", sleep).unwrap();
}
pub fn load_apis(lua: &Lua) {
lua.globals().set("fs", FS {}).unwrap();
}

View File

@ -1,7 +1,7 @@
use std::error::Error;
use std::{env, fs};
use tchoutchou::api::builtins::load_builtins;
use tchoutchou::api::{load_apis, load_builtins};
use tchoutchou::internal::core::runtime::Runtime;
#[tokio::main]
@ -30,6 +30,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
};
runtime.load(&load_builtins);
runtime.load(&load_apis);
runtime.start().await;
Ok(())

View File

@ -132,10 +132,13 @@ impl Service<Request<Body>> for Svc {
.unwrap();
match handler.call_async::<_, Res>((req, res)).await {
Ok(res) => Ok(Response::builder()
Ok(res) => {
let body = if res.json != "" { res.json } else { res.body };
Ok(Response::builder()
.status(res.status)
.body(Body::from(res.body))
.unwrap()),
.body(Body::from(body))
.unwrap())
}
Err(err) => {
eprintln!("{}", err);
Ok(Response::builder()