import { DataSource } from 'typeorm';

export async function handler(dataSource: DataSource, { user, query }) {
  const { current, size } = JSON.parse(query.pageInfo);

  const [list, [{ total }]] = await Promise.all([
    dataSource.query(`
      select
        r.id resourceId, r.name, rc.name classify, r.type, r.size,
        r.create_time createTime, r.creator, u.name creator
      from resource r
      left join resource_classify rc 
      on r.classify_id=rc.id
      left join user u
      on u.id=r.creator 
      where r.del_flag=0 and r.type!='folder' and r.creator='${user.userId}'
      ${query.type && `and r.type in ('${query.type.replace(/,/g, "','")}')`}
      limit ${(current - 1) * size},${size}
    `),
    dataSource.query(`
      select count(id) total
      from resource r
      where r.del_flag=0 and r.type!='folder' and r.creator='${user.userId}'
      ${query.type && `and r.type in ('${query.type.replace(/,/g, "','")}')`}
    `),
  ]);

  return { list, total: +total };
}
