Search code examples
postgresqlknex.jsfeathersjs

Feathersjs retrieve foreign key value through API


I am using PostgresSQL database with Feathersjs, connecting both through Knex. The database table (NewTable) was created with a foreign key, referencing to the users services.

Following describe the database table.

module.exports = function (app) {
  const db = app.get('knexClient');
  db.schema.createTableIfNotExists('NewTable', table => {
    table.increments('id').primary();
    table.integer('ownerId').references('users.id');
  })

I will receive the foreign key value of ownerId (in integer) when I query it through GET.

export function load(id) {
  return {
    types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
    promise: ({ app }) => app.service('NewTable').get(id)
  };
}

What is the proper way to retrieve the first_name column of the user instead of userId through the GET api?

Do I need to run another GET api within the hook of NewTable service to get the first_name column, or there is a better/easier way to do it?


Solution

  • Create a function like below within the hook of feathersjs.

    function populateUser() {
      return populate({
        schema: {
          include: [{
            nameAs: 'sentBy',
            service: 'users',
            parentField: 'ownerId',
            childField: 'id'
          }]
        }
      });
    }
    

    Use it within the hook to call it after the GET. The columns of user service will be included within the response.

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