Skip to content

Commit

Permalink
feat: 新增kernelApi
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed May 16, 2023
1 parent 155a825 commit 80ca482
Show file tree
Hide file tree
Showing 6 changed files with 232 additions and 29 deletions.
9 changes: 3 additions & 6 deletions src/utils/kernel-api.ts → src/Constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
* questions.
*/

/**
* 思源笔记服务端API v2.8.2
*/
class KernelApi {}

export default KernelApi
export const isDev = process.env.DEV_MODE === "true"
export const siyuanApiUrl = ""
export const siyuanApiToken = ""
93 changes: 93 additions & 0 deletions src/api/base-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, [email protected]
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

import { createLogger } from "../utils/simple-logger"
import { isDev, siyuanApiToken, siyuanApiUrl } from "../Constants"

/**
* 思源 API 返回类型
*/
export interface SiyuanData {
/**
* 非 0 为异常情况
*/
code: number

/**
* 正常情况下是空字符串,异常情况下会返回错误文案
*/
msg: string

/**
* 可能为 \{\}、[] 或者 NULL,根据不同接口而不同
*/
data: any[] | object | null | undefined
}

export class BaseApi {
private logger

constructor() {
this.logger = createLogger("base-api")
}

/**
* 向思源请求数据
*
* @param url - url
* @param data - 数据
*/
public async siyuanRequest(url: string, data: object): Promise<SiyuanData> {
const reqUrl = `${siyuanApiUrl}${url}`

const fetchOps = {
body: JSON.stringify(data),
method: "POST",
}
if (siyuanApiToken !== "") {
Object.assign(fetchOps, {
headers: {
Authorization: `Token ${siyuanApiToken}`,
},
})
}

if (isDev) {
this.logger.info("开始向思源请求数据,reqUrl=>", reqUrl)
this.logger.info("开始向思源请求数据,fetchOps=>", fetchOps)
}

const response = await fetch(reqUrl, fetchOps)
const resJson = await response.json()
if (isDev) {
this.logger.info("思源请求数据返回,resJson=>", resJson)
}

if (resJson.code === -1) {
throw new Error(resJson.msg)
}
return resJson.code === 0 ? resJson.data : null
}
}
113 changes: 113 additions & 0 deletions src/api/kernel-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, [email protected]
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

import { BaseApi, SiyuanData } from "./base-api"

/**
* 思源笔记服务端API v2.8.8
*
* @author terwer
* @version 1.0.0
* @since 1.0.0
*/
class KernelApi extends BaseApi {
/**
* 推送消息
*
* 参数
*
* ```json
* {
* "msg": "test",
* "timeout": 7000
* }
* ```
*
* timeout:消息持续显示时间,单位为毫秒。可以不传入该字段,默认为 7000 毫秒
*
* 返回值
*
* ```
* {
* "code": 0,
* "msg": "",
* "data": {
* "id": "62jtmqi"
* }
* }
*
* id:消息 ID
* ```
*
* @param msg 消息
*/
public async pushMsg(msg: string): Promise<SiyuanData> {
const msgObj = {
msg: msg,
timeout: 3000,
}
return await this.siyuanRequest("/api/notification/pushMsg", msgObj)
}

/**
* 推送报错消息
*
* 参数
*
* ```
* {
* "msg": "test",
* "timeout": 7000
* }
* ```
*
* timeout:消息持续显示时间,单位为毫秒。可以不传入该字段,默认为 7000 毫秒
*
* 返回值
*
* ```
* {
* "code": 0,
* "msg": "",
* "data": {
* "id": "qc9znut"
* }
* }
*
* id:消息 ID
* ```
*
* @param msg - 错误消息
*/
public async pushErrMsg(msg: string): Promise<SiyuanData> {
const msgObj = {
msg: msg,
timeout: 3000,
}
return await this.siyuanRequest("/api/notification/pushErrMsg", msgObj)
}
}

export default KernelApi
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,26 @@

import { App, IObject, Plugin } from "siyuan"
import { createLogger } from "./utils/simple-logger"
import KernelApi from "./api/kernel-api"
import { isDev } from "./Constants"

export default class ImporterPlugin extends Plugin {
private logger
private kernelApi

constructor(options: { app: App; id: string; name: string; i18n: IObject }) {
super(options)

this.logger = createLogger("index")
this.kernelApi = new KernelApi()
}

onload() {
if (isDev) {
this.logger.warn("DEV mode is enabled")
}

this.kernelApi.pushMsg("hello")
this.logger.info("Importer loaded")
}

Expand Down
9 changes: 9 additions & 0 deletions src/utils/simple-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
interface ILogger {
debug: (msg: string, obj?: any) => void
info: (msg: string, obj?: any) => void
warn: (msg: string, obj?: any) => void
error: (msg: string | Error, obj?: any) => void
}

Expand Down Expand Up @@ -65,6 +66,14 @@ export const createLogger = (name: string): ILogger => {
return {
debug: (msg: string, obj?: any) => log("DEBUG", msg, obj),
info: (msg: string, obj?: any) => log("INFO", msg, obj),
warn: (msg: string, obj?: any) => {
const time = formatDate(new Date())
if (obj) {
console.warn(`[${sign}] [${time}] [WARN] ${msg}`, obj)
} else {
console.warn(`[${sign}] [${time}] [WARN] ${msg}`)
}
},
error: (msg: string | Error, obj?: any) => {
if (typeof msg == "string") {
log("ERROR", msg, obj)
Expand Down
28 changes: 5 additions & 23 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,10 @@ import livereload from "rollup-plugin-livereload"
import { svelte } from "@sveltejs/vite-plugin-svelte"

const args = minimist(process.argv.slice(2))
const isWatch = args.watch || args.w
const isWatch = args.watch || args.w || false
const devDistDir = "/Users/terwer/Documents/mydocs/SiYuanWorkspace/public/data/plugins/siyuan-importer"
const distDir = isWatch ? devDistDir : "./dist"
// const mode = process.env.NODE_ENV
const mode = isWatch ? "development" : "production"

const defineEnv = () => {
const env = loadEnv(mode, process.cwd())
return {
"process.env": Object.entries(env).reduce((prev, [key, val]) => {
return {
...prev,
[key]: val,
}
}, {}),
}
}
const env = {
...defineEnv(),
// 下面可以自定义添加需要注入的环境变量
"process.env.NODE_ENV": mode,
}

console.log("mode=>", mode)
console.log("env=>", env)
console.log("isWatch=>", isWatch)
console.log("distDir=>", distDir)

Expand All @@ -52,8 +31,11 @@ export default defineConfig({

// https://github.com/vitejs/vite/issues/1930
// https://vitejs.dev/guide/env-and-mode.html#env-files
// https://github.com/vitejs/vite/discussions/3058#discussioncomment-2115319
// 在这里自定义变量
define: env,
define: {
"process.env.DEV_MODE": `"${isWatch}"`,
},

build: {
// 输出路径
Expand Down

0 comments on commit 80ca482

Please sign in to comment.