羽绒服加装遥控模型。

问题描述 投票:0回答:1

几天来,我被用feathersjs添加远程模型这么基本的东西卡住了。开始觉得自己真的很傻,这么基础的东西都卡住了。

如何创建一个标签,然后将其添加到帖子中。Tags.addPost({[...]})

如何访问sequelize模型?

https:/sequelize.orgmastermanualassocs.html#special-methods-mixins-added-to-instance

  const tags = sequelizeClient.define(
    'tags',
    {
      title: {
        type: DataTypes.STRING,
      },
    }
  const tags = sequelizeClient.define(
    'posts',
    {
      title: {
        type: DataTypes.STRING,
      },
    }

// [...]

  (posts as any).associate = function (models: any) {
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/

    const { tags, posts } = models;

    posts.belongsTo(tags);
    tags.hasMany(posts);
  };
  app.services.tags
    .create({
      title: 'myTag',
    })
    .then(myTag => {
      // has anybody found how to do something similar to
      // myTag.addPost({ title: 'myPost'}) ?
    })

feathersjs
1个回答
0
投票

这是我找到的部分解决方案。

基于这个 使用羽毛-客户和序列化多对多的关系。所以使用钩子,我就是这样按需加入远程模型的。

但还是要找到如何Tag.addPost({......})任何帮助,欢迎。

src/shared/hooks/index.ts

import { HookContext } from '@feathersjs/feathers';
import logger from '../logger';

// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
// Note that this will lead to infinite recursion on circular references.

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item: any) {
  return item && typeof item === 'object' && !Array.isArray(item);
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target: any, ...sources: [any]): any {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}


export default () => {
  return (context: HookContext) => {
    if (context.params && context.params.query && '$include' in context.params.query) {
      const { $include } = context.params.query;

      // Remove from the query so that it doesn't get included
      // in the actual database query
      delete context.params.query.$include;

      const sequelize = {
        include: new Array(),
        raw: false,
      };

      // console.log(`context.service.Model`, context.service.Model.name);
      // console.log(`context.service.Model.associations`, context.service.Model.associations);

      // see https://jsperf.com/array-coerce
      (Array.isArray($include) ? $include : [$include]).forEach((name: string) => {
        if (name in context.service.Model.associations) {
          sequelize.include.push({
            association: context.service.Model.associations[name],
            as: name,
          });
        } else {
          logger.error(
            `Requested association '${name}' of model '%s' doesn't exist. Available associations are: %O`,
            context.service.Model.name,
            context.service.Model.associations
          );
        }
      });

      // context.params.sequelize = { ...context.params.sequelize, ...sequelize };
      context.params.sequelize = mergeDeep(context.params.sequelize || {}, sequelize);
    }

    return Promise.resolve(context);
  };
};


编辑1:我们不想指定Model,而是关联 编辑2:如果关联不存在,不要在循环中崩溃,并记录错误。

src/app.hooks.ts

import { includeRemoteModels } from './shared/hooks';
// Application hooks that run for every service
// Don't remove this comment. It's needed to format import lines nicely.

export default {
  before: {
    all: [includeRemoteModels()],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: [],
  },

  after: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: [],
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: [],
  },
};

© www.soinside.com 2019 - 2024. All rights reserved.