Sequelize перья добавить / включить удаленную модель - PullRequest
0 голосов
/ 25 апреля 2020

Несколько дней, когда я застрял на чем-то столь основополагающем c, как добавление удаленных моделей с использованием перьев js. Начинаю чувствовать себя действительно глупо, чтобы застревать на чем-то, так что c. : - /

Как создать тег, а затем добавить его к сообщению: Tags.addPost({[...]})

Как получить доступ к моделям сиквелов?

https://sequelize.org/master/manual/assocs.html#special -methods- mixins-add-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'}) ?
    })

1 Ответ

0 голосов
/ 29 апреля 2020

Это часть решения, которое я нашел.

На основании этого Использование перья-клиента и продолжение отношения многие-ко-многим Итак, используя хуки, я включаю удаленные модели в Спрос.

Еще нужно найти, как пометить 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: мы дона Не хочу указывать модель, но связь
Редактировать 2: если связь не существует, не создавайте sh в l oop и журнал ошибок

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: [],
  },
};

...