feat(napi): support static class factory

This commit is contained in:
LongYinan 2021-11-05 18:31:36 +08:00
parent e74fe2fb94
commit e78cdd3c22
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
15 changed files with 150 additions and 15 deletions

View file

@ -48,9 +48,14 @@ Generated by [AVA](https://avajs.dev).
export class Animal {␊
readonly kind: Kind␊
constructor(kind: Kind, name: string)␊
static withKind(kind: Kind): Animal␊
get name(): string␊
set name(name: string)␊
whoami(): string␊
static getDogKind(): Kind␊
}␊
export class ClassWithFactory {␊
name: string␊
static withName(name: string): ClassWithFactory␊
}␊
`

View file

@ -15,6 +15,7 @@ import {
getCwd,
Animal,
Kind,
ClassWithFactory,
CustomNumEnum,
enumToI32,
listObjKeys,
@ -81,6 +82,20 @@ test('class', (t) => {
t.is(dog.name, '可乐')
})
test('class factory', (t) => {
const duck = ClassWithFactory.withName('Default')
t.is(duck.name, 'Default')
duck.name = '周黑鸭'
t.is(duck.name, '周黑鸭')
const doge = Animal.withKind(Kind.Dog)
t.is(doge.name, 'Default')
doge.name = '旺财'
t.is(doge.name, '旺财')
})
test('callback', (t) => {
getCwd((cwd) => {
t.is(cwd, process.cwd())

View file

@ -38,8 +38,13 @@ export function getBuffer(): Buffer
export class Animal {
readonly kind: Kind
constructor(kind: Kind, name: string)
static withKind(kind: Kind): Animal
get name(): string
set name(name: string)
whoami(): string
static getDogKind(): Kind
}
export class ClassWithFactory {
name: string
static withName(name: string): ClassWithFactory
}

View file

@ -19,6 +19,14 @@ impl Animal {
Animal { kind, name }
}
#[napi(factory)]
pub fn with_kind(kind: Kind) -> Self {
Animal {
kind,
name: "Default".to_owned(),
}
}
#[napi(getter)]
pub fn get_name(&self) -> &str {
self.name.as_str()

View file

@ -0,0 +1,14 @@
use napi::bindgen_prelude::*;
#[napi]
pub struct ClassWithFactory {
pub name: String,
}
#[napi]
impl ClassWithFactory {
#[napi(factory)]
pub fn with_name(name: String) -> Self {
Self { name }
}
}

View file

@ -7,6 +7,7 @@ mod array;
mod r#async;
mod callback;
mod class;
mod class_factory;
mod either;
mod r#enum;
mod error;