GithubHelp home page GithubHelp logo

halo-dev / js-sdk Goto Github PK

View Code? Open in Web Editor NEW
21.0 4.0 16.0 1.32 MB

A collection of tools for interacting with Halo's APIs.

Home Page: https://halo-js-sdk.vercel.app

License: MIT License

JavaScript 5.90% TypeScript 94.06% Shell 0.04%
halo sdk-js

js-sdk's Introduction

Halo logo

Halo SDK

Project Build npm npm npm version

一个与 Halo api 交互的工具集

English Document

特性

  • 封装认证以简化开发.
  • 异常处理
  • 使用 Halo rest api 更方便
  • 使用 TypeScript 编写,更明确的参数和返回值类型,更好的代码提示

管理后台 API 库

安装

使用 npm 方式安装示例如下:

npm install @halo-dev/admin-api --save

使用示例

以下是一个获取后台文章列表的简单示例:

import { AdminApiClient, HaloRestAPIClient } from "@halo-dev/admin-api";
//halo http 请求客户端.
const haloRestApiClient = new HaloRestAPIClient({
  baseUrl: process.env.HALO_BASE_URL,
  auth: { adminToken: "halo admin token" },
});
// 通过 haloRestApiCLient 创建 adminApiClient。
const haloAdminClient = new AdminApiClient(haloRestApiClient);
// 获取文章列表
haloAdminClient.post.list().then((res) => {
  console.log(res);
});

关于如何通过用户名和密码进行自动认证,这里提供了一个示例 example

由于 @halo-dev/admin-api 依赖 @halo-dev/rest-api-client,而其是基于 axios 进行 http 通信的,因此如果你有需要的话,可以使用 axios, 的拦截器对 halo api 的请求与响应进行一些处理。

import axios from "axios";

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

@halo-dev/content-api 也可以这样使用拦截器。

前台 API 库

使用 npm 安装示例如下:

npm install @halo-dev/content-api --save

使用示例

同样我们使用一个获取博客前台文章列表的示例如下:

import { ContentApiClient, HaloRestAPIClient } from "@halo-dev/content-api";
// 创建 halo http 请求客户端
const haloRestApiClient = new HaloRestAPIClient({
  baseUrl: process.env.HALO_BASE_URL,
  auth: { apiToken: process.env.HALO_API_TOKEN },
});
// 通过 http 客户端创建 halo 前台 api 客户端
const haloContentClient = new ContentApiClient(haloRestApiClient);
// 获取文章列表
haloContentClient.post.list().then((res) => {
  console.log(res);
});

Halo Rest API Http 通信库

安装

你可以使用 npm 安装它,示例如下:

npm install @halo-dev/rest-api-client

使用 requireimport 导入

// CommonJS
const { HaloRestAPIClient } = require("@halo-dev/rest-api-client");
// ES modules
import { HaloRestAPIClient } from "@halo-dev/rest-api-client";

使用示例

const client = new HaloRestAPIClient({
  baseUrl: "https://example.halo.run",
  // Use password authentication
  auth: {
    username: process.env.HALO_USERNAME,
    password: process.env.HALO_PASSWORD,
  },
});

auth 参数为认证方式,支持以下几种认证方式,示例如下:

  1. 使用 API token 认证,它适用于 halo 博客前台 api 认证
auth: {
  apiToken: process.env.HALO_API_TOKEN;
}
  1. 使用 Admin token 认证,它适用于 halo 后台管理 api 认证
auth: {
  adminToken: process.env.HALO_ADMIN_TOKEN;
}
  1. 使用自定义请求头认证方式
auth: {
    type: "customizeAuth",
    authHeader: "Admin-Authorization",
      getToken () {
      return localStorage.getItem ("Access_Token")
    }
}
  1. 使用 OAuth2 Bearer token 的认证方式,最终会在请求头添加 Authorization: bearer some-token
auth: {
  oAuthToken: process.env.HALO_OAUTH_TOKEN;
}

Basic 认证

会在请求头添加例如 Authorization: Basic dXNlci1jbGllbi1zZWNyZXQtODg4OA== 这样的 pair

const client = new HaloRestAPIClient({
  baseUrl: "https://example.halo.run",
  // Use basic authentication
  basicAuth: { username: "user", password: "password" },
});

另外还支持通过提供一个 TokenProvider 来接管 halo 的认证,这样不需要在考虑如何实现登录和 token 过期怎么续期的逻辑,示例如下:

import {
  HaloRestAPIClient,
  LocalStorageTokenStore,
  // FileTokenStore,
  // TokenStore,
  DefaultTokenProvider,
} from "@halo-dev/rest-clint-api";

// Use LocalStorageTokenStore to persistence AccessToken to localStorage (in browser only)
//you can use FileTokenStore if in the Node environment.
// If there is no suitable Token store implemention, you can implement your own token storage strategy through the TokenStore interface.
const localStorageTokenStore = new LocalStorageTokenStore();

//halo api base url.
const baseUrl = process.env.VUE_APP_BASE_URL;

const haloRestApiClient = new HaloRestAPIClient({
  baseUrl: baseUrl,
});

const buildTokenProvider = (credentials) => {
  return new DefaultTokenProvider(
    {
      ...credentials,
    },
    baseUrl,
    localStorageTokenStore
  );
};

const tokenProvider = buildTokenProvider({
  username: "your halo username",
  password: "your password",
});
haloRestApiClient.setTokenProvider(tokenProvider);
//now you can use haloRestApiClient to build your api client

完整的例子可以点 这里

发送 Http 请求

const haloRestApiClient = new HaloRestAPIClient({
  baseUrl: "https://example.halo.run",
  basicAuth: { username: "user", password: "password" },
});
//build http client to perform http request
const client = haloRestApiClient.buildHttpClient();

//api parameters
const parameters = {};
//http get
client.get("https://example.halo.run", parameters);
//http post
client.post("https://example.halo.run", parameters);

Logger 日志库

安装

使用 npm 安装示例如下:

npm install @halo-dev/logger --save

主要概念

@halo-dev/logger 包支持按从最详细到最不详细的顺序指定的以下日志级别:

  • debug
  • info
  • warning
  • error

当以编程方式或通过 HALO_LOG_LEVEL 环境变量设置日志级别时,使用小于或等于您选择的日志级别时写入的任何日志都将被显示。

例如,将日志级别设置为 warning 将导致所有日志级别为 warningerror 的日志被显示。

使用示例

示例 1 - 基本使用

import * as Logger from "@halo-dev/logger";
Logger.setLogLevel ("info");

//operations will now emit info, warning, and error logs

//create a namespaced logger
const logger = Logger.createClientLogger ("posts");
const client = new AdminApiClient (/* params */);
client.post.list ()
  .then (res => {
    /* write an info log */
    logger.info ("Successfully acquired a list of articles", res);
  })
  .catch (e => { /* do work */ });
});

示例 2 - 覆盖原先日志输出方式

import { HaloLogger, setLogLevel } from "@halo-dev/logger";

setLogLevel("warning");

//override logging to output to console.log (default location is stderr)
HaloLogger.log = (...args) => {
  console.log(...args);
};
HaloLogger.log("hello world!");

License

MIT license

js-sdk's People

Contributors

gungnir479 avatar guqing avatar jaxsonwang avatar junweilife avatar ruibaby avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

js-sdk's Issues

维护计划

不知道这个项目官方是否还有维护的打算,今天研究了一波,想用ssr撸个主题,路子打通了,也进行可行性验证了,然而一瞅,三年没更新了~ /(ㄒoㄒ)/~~

在 Vite 下使用异常

[vite] Internal server error: Failed to resolve entry for package "@halo-dev/admin-api". The package may have incorrect main/module/exports specified in its package.json.
  Plugin: vite:import-analysis
  File: /Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/src/utils/api-client.ts
      at resolvePackageEntry (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:32628:15)
      at tryNodeResolve (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:32447:11)
      at Context.resolveId (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:32330:28)
      at Object.resolveId (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:44739:55)
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async TransformContext.resolve (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:44541:23)
      at async normalizeUrl (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:70738:34)
      at async TransformContext.transform (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:70873:57)
      at async Object.transform (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:44796:30)
      at async transformRequest (/Users/ryanwang/Workspace/github/halo-dev/halo-admin-next/node_modules/vite/dist/node/chunks/dep-0ed4fbc0.js:60267:29) (x5)

themeClient.saveSettings错误

themeClient.saveSettings发送的内容应该是直接的配置信息,例如:

{a:100, b:100}

而不该是

{settings:{a:100,b:100}}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.