mike-works / sql-fundamentals

Mike North's SQL Fundamentals and Professional SQL Courses
https://frontendmasters.com/courses/sql-fundamentals/
BSD 3-Clause "New" or "Revised" License
169 stars 108 forks source link

Object merge is not working #53

Open EddyVinck opened 6 years ago

EddyVinck commented 6 years ago

https://github.com/mike-works/sql-fundamentals/blob/master/src/data/orders.js#L40-L43

I tried it outside of the function and the result is as expected.

const DEFAULT_ORDER_COLLECTION_OPTIONS = Object.freeze(
  /** @type {OrderCollectionOptions}*/ ({
    order: 'asc',
    page: 1,
    perPage: 20,
    sort: 'id'
  })
);

const optsTest = {
  page: '2',
  perPage: 30
};

let optionsTest = {
  ...DEFAULT_ORDER_COLLECTION_OPTIONS,
  ...optsTest
};

console.log(optionsTest); 
-> RESULT: { order: 'asc', page: '2', perPage: 30, sort: 'id' }

Pulling an object literal into the function also doesn't work

export async function getAllOrders(opts = {}, whereClause = '') {
  // Combine the options passed into the function with the defaults

  /** @type {OrderCollectionOptions} */
  let options = {
    ...{
      order: 'asc',
      page: 1,
      perPage: 20,
      sort: 'id'
    },
    ...opts
  };

  console.log(options);
  -> RESULT: { order: undefined, page: '2', perPage: 30, sort: undefined }

  const db = await getDb();
  return await db.all(sql`
SELECT ${ALL_ORDERS_COLUMNS.join(',')}
FROM CustomerOrder
${whereClause} 
ORDER BY ${options.sort} ${options.order}
LIMIT ${options.perPage} 
OFFSET ${options.page * options.perPage}`);
}

When I log options inside the function I get the following:

export async function getAllOrders(opts = {}, whereClause = '') {
  // Combine the options passed into the function with the defaults

  /** @type {OrderCollectionOptions} */
  let options = {
    ...DEFAULT_ORDER_COLLECTION_OPTIONS,
    ...opts
  };

  console.log(options);
  -> RESULT: { order: undefined, page: '2', perPage: 30, sort: undefined }

  const db = await getDb();
  return await db.all(sql`
SELECT ${ALL_ORDERS_COLUMNS.join(',')}
FROM CustomerOrder
${whereClause} 
ORDER BY ${options.sort} ${options.order}
LIMIT ${options.perPage} 
OFFSET ${options.page * options.perPage}`);
}

I haven't been able to fix it though.

[edit]

This one worked for some reason

export async function getAllOrders(opts = {}, whereClause = '') {
  // Combine the options passed into the function with the defaults

  const options2 = {
    ...{
      order: 'asc',
      page: 1,
      perPage: 20,
      sort: 'id'
    },
    ...{
      page: '2',
      perPage: 30
    }
  };

  console.log(options2);
  -> RESULT: { order: 'asc', page: '2', perPage: 30, sort: 'id' }

  const db = await getDb();
  return await db.all(sql`
SELECT ${ALL_ORDERS_COLUMNS.join(',')}
FROM CustomerOrder
${whereClause} 
ORDER BY ${options2.sort} ${options2.order}
LIMIT ${options2.perPage} 
OFFSET ${options2.page * options2.perPage}`);
}