4.2.4 框架之网络请求-HttpClient

oinone提供统一的网络请求底座,基于graphql二次封装

一、初始化

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setMiddleware() // 必须设置,请求回调。具体查看文章https://shushi.yuque.com/yqitvf/oinone/vwo80g
http.setBaseURL() // 必须设置,后端请求的路径

图4-2-4-1 初始化代码示例

二、HttpClient详细介绍

获取实例

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();

图4-2-4-2 获取实例

接口地址

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setBaseURL('接口地址');
http.getBaseURL(); // 获取接口地址

图4-2-4-3 接口地址

请求头

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setHeader({key: value});

图4-2-4-4 请求头

variables

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setExtendVariables((moduleName: string) => {
 return customFuntion();

});

图4-2-4-5 variables

回调

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setMiddleware([middleware]);

图4-2-4-6 回调

业务使用-query

private http = HttpClient.getInstance();
private getTestQuery = async () => {
 const query = `gql str`;
 const result = await this.http.query('module name', query);
 console.log(result)
 return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回
};

图4-2-4-7 业务使用-query

业务使用-mutate

private http = HttpClient.getInstance();

private getTestMutate = async () => {
  const mutation = `gql str`;

  const result = await this.http.mutate('module name', mutation);
    console.log(result)
  return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回
};

图4-2-4-8 业务使用-mutate

三、如何使用HttpClient

初始化

在项目目录src/main.ts下初始化httpClient

初始化必须要做的事:

  • 设置服务接口链接

  • 设置接口请求回调

业务实战

前文说到自定义新增宠物表单,让我们在这个基础上加入我们的httpClient;

第一步新增service.ts

image.png

图4-2-4-8 新增service.ts

service.ts

import { HttpClient } from '@kunlun/dependencies';

const addPetMutate = async (modelName, data) => {
    const http = HttpClient.getInstance();
    const mutateGql = `mutation{
    petMutation{
      addPet(data:${data})
       {
        id
      }
    }
  }`;

    const result = await http.mutate('pet', mutateGql);
    return (result as any).data['petMutation']['addPet'];
};

export { addPetMutate };

图4-2-4-9 service.ts

第二步业务中使用

import { constructOne, queryOne, SPI, ViewWidget, Widget, IModel, getModelByUrl, getModel, getIdByUrl, FormWidgetV3, CustomWidget, CallChaining } from '@kunlun/dependencies';
import PetFormView from './PetFormView.vue';
// 引入
import { addPetMutate } from './service';

@SPI.ClassFactory(CustomWidget.Token({ widget: 'PetForm' }))
export class PetFormViewWidget extends FormWidgetV3 {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(PetFormView);
    return this;
  }

  /**
   * 数据提交
   * @protected
   */
  @Widget.Reactive()
  @Widget.Inject()
  protected callChaining: CallChaining | undefined;

  private modelInstance!: IModel;

  /**
   * 重要!!!!
   * 当字段改变时修改formData
   * */
  @Widget.Method()
  public onFieldChange(fieldName: string, value) {
    this.setDataByKey(fieldName, value);
  }

  /**
   * 表单编辑时查询数据
   * */
  public async fetchData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance?.modelFields;
    try {
      const id = getIdByUrl();
      const data = (await queryOne(this.modelInstance.model, (content[0] || { id }) as Record<string, string>, fields, variables, context)) as Record<string, unknown>;

      this.loadData(data);
      this.setBusy(false);
      return data;
    } catch (e) {
      console.error(e);
    } finally {
      this.setBusy(false);
    }
  }

  /**
   * 新增数据时获取表单默认值
   * */
  @Widget.Method()
  public async constructData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance.modelFields;
    const reqData = content[0] || {};
    const data = await constructOne(this.modelInstance!.model, reqData, fields, variables, context);
    return data as Record<string, unknown>;
  }

  @Widget.Method()
  private async reloadData() {
    const data = await this.constructData();
    // 覆盖formData
    this.setData(data);
  }

  @Widget.Method()
  public onChange(name, value) {
    this.formData[name] = value;
  }

  protected async mounted() {
    super.mounted();
    const modelModel = getModelByUrl();
    this.modelInstance = await getModel(modelModel);
    this.fetchData();
    // 数据提交钩子函数!!!
    this.callChaining?.callBefore(() => {
      return this.formData;
    });
  }

  @Widget.Method()
  private async addPet() {
    // 调用
    const data = await addPetMutate('petModule', this.getData());
  }
}

图4-2-4-10 业务中使用

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9305.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:33
下一篇 2024年5月23日 am8:35

相关推荐

  • 构件类

    1.构件类 1.1 延时 当下一个节点动作需要一段时间之后再发生时,可以使用延时节点。延时节点包含两种延时方式:1、延至指定日期,2、延时一段时间。 选择延至指定日期时,可以选择延至模型字段的时间或自定义时间,如果模型字段只包含日期则必填指定时辰。如果选择自定义则需要分别指定日期和时辰。 选择延时一段时间时,至少需要填“天、小时、分钟”中的一项。 1.2 条件分支 使不同条件的数据执行不同的分支流程。需要设置分支条件、添加满足条件的动作、也可以增删条件分支。 必须将分支条件填写完整流程才能正常进行。当只有两个分支时点击删除任一分支会删除整个条件分支。 1.3 审批分支 审批分支是一种特殊的条件分支。审批分支只能添加在审批节点下方。因为审批只存在通过和拒绝两种条件,所以无法添加其他条件,并且点击任意条件的叉都会删除整个条件分支。同时若审批节点被删除,审批分支也会同时删除。 1.4 子流程 一些高度重复的流程节点可以创建成子流程,在主流程中引用子流程,减少流程的重复配置。选择子流程时只能选择当前流程中有用到的模型下并且在启用状态的子流程,也可以在创建子流程节点处设置新增子流程。子流程的执行方式有两种:子流程可以和后续节点同时执行,也可以设置子流程执行完后再执行后续节点。 子流程与普通正常流程不同,不包含触发方式,普通流程流转到子流程节点即为子流程的触发条件,添加完节点动作之后发布即可。在不新增数据的情况下,子流程中只能使用该子流程对应模型的字段数据。

    2024年5月23日
    1.3K00
  • 致Oinone读者

    欢迎来到Oinone生态,我们为您提供了一站式低代码商业支撑平台,数式科技已经用其服务了如中烟、得力、上海电气、中航金网、雾芯科技等多个知名企业,我们的技术实力在商业场景得到了很好的验证。我们希望通过开源Oinone项目,为中国软件行业带来变革,提升整体工程化水平,与广大软件工程师一起为客户创造价值!《Oinone 7天从入门到精通》一书是Oinone开源项目的配套书籍,系统化地介绍了如何基于Oinone开源项目,快速开发高质量的软件系统。此外,如果您开发的项目是用于商业化而非企业自用,我们还为您提供了一种可选的商业化变现途径:申请成为Oinone的合作伙伴,并提交相关产品,详情请访问 www.oinone.top 网站。 书籍纲领 本书的章节安排如下: 第一章至第二章:【揭开面纱,理解Oinone】和【Oinone的技术独特性】。这两个章节可以帮助您更好地理解我们设计Oinone的初衷以及特性的由来。 第三章:面向研发人员的【Oinone的基础入门】。如果您是专业的研发人员,本章可以帮助您快速上手并做出业务系统。只要按着里面的case一步步操作下来就可以。 第四章至第六章:面向研发人员的【Oinone的高级特性】、【Oinone的CDM】、【Oinone的通用能力】。这三篇章节重点介绍了Oinone的高级技术特性、提供的通用数据模型和通用基础能力。它们能够帮助我们更快地进行业务开发,从容应对业务的特殊场景要求,比较适合进阶的研发人员。 第七章:面向非研发人员的【Oinone的设计器们】和【Oinone的低无一体】。如果您并不是专业的研发人员,本章可以帮助您通过使用Oinone的无代码可视化设计器轻松自主解决业务需求,并且当可视化设计器满足不了的时候,您还可以在【Oinone的低无一体】中找到方式,并寻求研发帮助

    Oinone 7天入门到精通 2024年5月23日
    1.3K00
  • 4.2.2 框架之MessageHub

    一、MessageHub 请求出现异常时,提供”点对点“的通讯能力 二、何时使用 错误提示是用户体验中特别重要的组成部分,大部分的错误体现在整页级别,字段级别,按钮级别。友好的错误提示应该是怎么样的呢?我们假设他是这样的 与用户操作精密契合 当字段输入异常时,错误展示在错误框底部 按钮触发服务时异常,错误展示在按钮底部 区分不同的类型 错误 成功 警告 提示 调试 简洁易懂的错误信息 在oinone平台中,我们怎么做到友好的错误提示呢?接下来介绍我们的MessageHub,它为自定义错误提示提供无限的可能。 三、如何使用 订阅 import { useMessageHub, ILevel } from "@kunlun/dependencies" const messageHub = useMessageHub('当前视图的唯一标识'); /* 订阅错误信息 */ messageHub.subscribe((errorResult) => { console.log(errorResult) }) /* 订阅成功信息 */ messageHub.subscribe((errorResult) => { console.log(errorResult) }, ILevel.SUCCESS) 图4-2-2-1 订阅的示例代码 销毁 /** * 在适当的时机销毁它 * 如果页面逻辑运行时都不需要销毁,在页面destroyed是一定要销毁,重要!!! */ messageHub.unsubscribe() 图4-2-2-2 销毁的示例代码 四、实战 让我们把3.5.7.5【自定义视图-表单】一文中的自定义表单进行改造,加入我们的messageHub,模拟在表单提交时,后端报错信息在字段下方给予提示。 Step1 (后端)重写PetType的创建函数 重写PetType的创建函数,在创建逻辑中通过MessageHub返回错误信息,返回错误信息的同时要设置paths信息方便前端处理 @Action.Advanced(name = FunctionConstants.create, managed = true) @Action(displayName = "确定", summary = "创建", bindingType = ViewTypeEnum.FORM) @Function(name = FunctionConstants.create) @Function.fun(FunctionConstants.create) public PetType create(PetType data){ List<Object> paths = new ArrayList<>(); paths.add("demo.PetType"); paths.add("kind"); PamirsSession.getMessageHub().msg(new Message().msg("kind error").setPath(paths).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR)); List<Object> paths2 = new ArrayList<>(); paths2.add("demo.PetType"); paths2.add("name"); PamirsSession.getMessageHub().msg(new Message().msg("name error").setPath(paths2).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR)); // data.create(); return data; } 图4-2-2-3 (后端)重写PetType的创建函数 Step 2 修改PetForm.vue <template> <div class="petFormWrapper"> <form :model="formState" @finish="onFinish"> <a-form-item label="品种种类" id="name" name="kind" :rules="[{ required: true, message: '请输入品种种类!', trigger: 'focus' }]"> <a-input v-model:value="formState.kind" @input="(e) => onNameChange(e, 'kind')" /> <span style="color: red">{{ getServiceError('kind') }}</span> </a-form-item> <a-form-item label="品种名" id="name" name="name" :rules="[{ required: true, message: '请输入品种名!', trigger: 'focus' }]"> <a-input v-model:value="formState.name" @input="(e) => onNameChange(e, 'name')" /> <span style="color: red">{{ getServiceError('name') }}</span> </a-form-item> </form> </div> </template>- <script lang="ts"> import { defineComponent, reactive…

    2024年5月23日
    1.2K00
  • 3.2.2 启动前端工程

    本节核心是带大家直观的感受下我们上节构建的demo模块,并搭建前端环境为后续学习打下基础 一、使用vue-cli构建工程 ##demo-front是项目名,可以替换成自己的 vue create –preset http://ss.gitlab.pamirs.top/:qilian/pamirs-archetype-front4 –clone demo-front –registry http://nexus.shushi.pro/repository/kunlun/ 图3-2-2-1 使用vue-cli构建工程 如果启动报错,清除node_modules后重新npm i mac清除命令:npm run cleanOs windows清除命令: npm run clean 若安装失败,检查本地node、npm、vue对应的版本 图3-2-2-2 检查本地的版本 或者下载前端工程本地运行[oinone-front.zip](oinone-front)(575 KB) 二、启动前端工程 找到README.MD文件,根据文件一步一步操作就行。 找到vue.config.js文件,修改devServer.proxy.pamirs.target为后端服务的地址和端口 const WidgetLoaderPlugin = require('@kunlun/widget-loader/dist/plugin.js').default; const Dotenv = require('dotenv-webpack'); module.exports = { lintOnSave: false, runtimeCompiler: true, configureWebpack: { module: { rules: [ { test: /\.widget$/, loader: '@kunlun/widget-loader' } ] }, plugins: [new WidgetLoaderPlugin(), new Dotenv()], resolveLoader: { alias: { '@kunlun/widget-loader': require.resolve('@kunlun/widget-loader') } } }, devServer: { port: 8080, disableHostCheck: true, progress: false, proxy: { pamirs: { // 支持跨域 changeOrigin: true, target: 'http://127.0.0.1:8090' } } } }; 图3-2-2-3 修改后端服务地址与端口 注:要用localhost域名访问,.env文件这里也要改成localhost。如果开发中一定要出现前后端域名不一致,老版本Chrome会有问题,修改可以请参考https://www.cnblogs.com/willingtolove/p/12350429.html 。或者下载新版本Chrome 进入前端工程demo-front文件目录下,执行 npm run dev,最后出现下图就代表启动成功 图3-2-2-4 前端启动成功提示 使用 http://127.0.0.1:8081/login 进行访问,并用admin账号登陆,默认密码为admin 图3-2-2-5 系统登陆页面 点击左上角进行应用切换,会进入App Finder页面,可以看到所有已经安装的应用,可以对照boot的yml配置文件看。但细心的小伙伴应该注意到了,在App Finder页面出现的应用跟我们启动工程yml配置文件中加载的启动模块数不是一一对应的,同时也没有看到我们demo模块。 图3-2-2-6 已安装应用界面 boot工作的yml文件中加载模块 App Finder的应用 说明 – base- common- sequence- expression 无 模块的application = false,为非应用类的模块 – resource – user – auth – business- message – apps- my_center(show=INACTIVE )- sys_setting (show=INACTIVE ) 有 模块的application = true,为应用类的模块但show=INACTIVE 的则不展示,通过以下方式定义:@Module(show = ActiveEnum.INACTIVE) – demo_core 无 刚建的oinoneDemo工程,默认为false 设计器:无 设计器:无 因为boot中没有加载设计器模块,所以App Finder中的设计器tab选项卡下没有应用 表3-2-2-1 boot工作的yml文件中加载模块及App Finder应用说明 只需要修改oinoneDemo工程的模块定义如下图,那么就可以在App Finder页面看见“oinoneDemo工程”。 图3-2-2-7 修改模块的application属性为true 图3-2-2-8 在App Finder 页面即可看见“OinoneDemo工程” 目前oinone的Demo模块还是一个全空的模块,所以我们点击后会进入一个空白页面。在后续的学习过程中我们会不断完善该模块。 至此恭喜您,前端工程已经启动完成。 三、前端工程结构介绍 ├── public 发布用的目录,index.html入口文件将在这里 │ ├── src 源代码…

    2024年5月23日
    1.4K00

Leave a Reply

登录后才能评论