2021-09-24 18:01:54 +09:00
|
|
|
use std::{collections::HashMap, fs};
|
|
|
|
|
2021-09-23 02:29:09 +09:00
|
|
|
use napi::bindgen_prelude::*;
|
|
|
|
|
|
|
|
use crate::r#enum::Kind;
|
|
|
|
|
2021-09-24 14:00:35 +09:00
|
|
|
/// `constructor` option for `struct` requires all fields to be public,
|
|
|
|
/// otherwise tag impl fn as constructor
|
|
|
|
/// #[napi(constructor)]
|
|
|
|
#[napi]
|
2021-09-23 02:29:09 +09:00
|
|
|
pub struct Animal {
|
|
|
|
#[napi(readonly)]
|
|
|
|
pub kind: Kind,
|
2021-09-24 14:00:35 +09:00
|
|
|
name: String,
|
2021-09-23 02:29:09 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
#[napi]
|
|
|
|
impl Animal {
|
2021-09-24 14:00:35 +09:00
|
|
|
#[napi(constructor)]
|
2021-09-23 02:29:09 +09:00
|
|
|
pub fn new(kind: Kind, name: String) -> Self {
|
|
|
|
Animal { kind, name }
|
|
|
|
}
|
|
|
|
|
2021-09-24 14:00:35 +09:00
|
|
|
#[napi(getter)]
|
|
|
|
pub fn get_name(&self) -> &str {
|
|
|
|
self.name.as_str()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[napi(setter)]
|
|
|
|
pub fn set_name(&mut self, name: String) {
|
|
|
|
self.name = name;
|
|
|
|
}
|
|
|
|
|
2021-09-23 02:29:09 +09:00
|
|
|
#[napi]
|
|
|
|
pub fn whoami(&self) -> String {
|
|
|
|
match self.kind {
|
|
|
|
Kind::Dog => {
|
|
|
|
format!("Dog: {}", self.name)
|
|
|
|
}
|
|
|
|
Kind::Cat => format!("Cat: {}", self.name),
|
|
|
|
Kind::Duck => format!("Duck: {}", self.name),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-09-24 18:01:54 +09:00
|
|
|
|
|
|
|
#[napi(constructor)]
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
struct PackageJson {
|
|
|
|
pub name: String,
|
|
|
|
pub version: String,
|
|
|
|
pub dependencies: Option<HashMap<String, String>>,
|
|
|
|
#[serde(rename = "devDependencies")]
|
|
|
|
pub dev_dependencies: Option<HashMap<String, String>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[napi]
|
|
|
|
fn read_package_json() -> Result<PackageJson> {
|
|
|
|
let raw = fs::read_to_string("package.json")?;
|
|
|
|
let p: PackageJson = serde_json::from_str(&raw)?;
|
|
|
|
Ok(p)
|
|
|
|
}
|