Skip to content

Commit

Permalink
assets-27 #27 create enpoint for studyId selection
Browse files Browse the repository at this point in the history
  • Loading branch information
TIL-EBP committed Apr 11, 2024
1 parent ecb9e43 commit 5ec7845
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 72 deletions.
12 changes: 11 additions & 1 deletion apps/server-asset-sg/src/app/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Controller, Get, HttpException, Param, Query, Req, Res } from '@nestjs/common';
import { Body, Controller, Get, HttpException, Param, Post, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import * as E from 'fp-ts/Either';
import * as D from 'io-ts/Decoder';
Expand Down Expand Up @@ -27,6 +27,16 @@ export class AppController {
return e.right;
}

@Post('assets')
async searchAssets(@Body() body: { ids: string[] }) {
const e = await this.appService.searchAssetsByStudyIds(body.ids)();
if (E.isLeft(e)) {
console.error(e.left);
throw new HttpException(e.left.message, 500);
}
return e.right;
}

@Get('asset')
// async findAssetsByPolygon(@Query() polygon: [number, number][]) {
async findAssetsByPolygon(@Req() req: Request) {
Expand Down
103 changes: 63 additions & 40 deletions apps/server-asset-sg/src/app/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { sequenceS } from 'fp-ts/Apply';
import * as A from 'fp-ts/Array';
import * as E from 'fp-ts/Either';
import { contramap } from 'fp-ts/Eq';
import { Lazy, flow, pipe } from 'fp-ts/function';
import { flow, Lazy, pipe } from 'fp-ts/function';
import * as NEA from 'fp-ts/NonEmptyArray';
import * as N from 'fp-ts/number';
import * as O from 'fp-ts/Option';
Expand All @@ -15,17 +15,17 @@ import * as TE from 'fp-ts/TaskEither';
import * as C from 'io-ts/Codec';
import * as D from 'io-ts/Decoder';

import { DT, decodeError, isNotNil, unknownToError, unknownToUnknownError } from '@asset-sg/core';
import { decodeError, DT, isNotNil, unknownToError, unknownToUnknownError } from '@asset-sg/core';
import {
AssetSearchParams,
BaseAssetDetail,
DateId,
DateIdFromDate,
makeUsageCode,
SearchAssetResult,
SearchAssetResultCodec,
SearchAssetResultOutput,
UsageCode,
makeUsageCode,
} from '@asset-sg/shared';

import { notFoundError } from './errors';
Expand All @@ -36,11 +36,16 @@ import {
SearchAssetElasticResultDecoder,
SearchResultsElasticData,
} from './models/SearchAssetElasticResult';
import { postgresStudiesByAssetId } from './postgres-studies/postgres-studies';
import {
createAllStudyQuery,
decodeStudyQueryResult,
postgresStudiesByAssetId,
} from './postgres-studies/postgres-studies';
import { PrismaService } from './prisma/prisma.service';
import { createElasticSearchClient } from './search/elastic-search-client';
import { findAssetsByPolygon } from './search/find-assets-by-polygon';
import { executeAssetQuery, findAssetsByPolygon } from './search/find-assets-by-polygon';
import { searchAssets } from './search/find-assets-by-search-text';
import { makeSearchAssetResult } from './search/search-asset';

@Injectable()
export class AppService {
Expand All @@ -50,7 +55,9 @@ export class AppService {
const polygonParam = polygon.map(point => `${point[0]} ${point[1]}`).join(',');

const result = await this.prismaService.$queryRawUnsafe(
`select id, accident_uid, year, month, canton, ST_AsText(geom) as geom from bicycle_accidents where ST_INTERSECTS(geom, ST_GeomFromText('POLYGON((${polygonParam}))', 2056))`,
`select id, accident_uid, year, month, canton, ST_AsText(geom) as geom
from bicycle_accidents
where ST_INTERSECTS(geom, ST_GeomFromText('POLYGON((${polygonParam}))', 2056))`,
);
return { result };
}
Expand Down Expand Up @@ -110,10 +117,29 @@ export class AppService {
}),
);
}

// findAssetsByPolygon(polygon: [number, number][]) {
// return findAssetsByPolygon(this.prismaService, polygon);
// }

searchAssetsByStudyIds(ids: string[]): TE.TaskEither<Error, SearchAssetResult> {
const whereClause = `study_id in (${ids.map(id => `'${id}'`).join(',')})`;
return pipe(
TE.tryCatch(() => this.prismaService.$queryRawUnsafe(createAllStudyQuery(whereClause)), unknownToError),
TE.chain(decodeStudyQueryResult),
TE.chain(studies => {
const assetIds = studies.map(study => study.assetId);
return pipe(
executeAssetQuery(this.prismaService, assetIds),
TE.map(assets => [assets, studies] as const),
);
}),
TE.map(([assets, studies]) => {
return makeSearchAssetResult(assets, studies);
}),
);
}

// findAssetsByPolygon(polygon: [number, number][]) {
// const polygonParam = polygon.map(point => `${point[0]} ${point[1]}`).join(',');

Expand Down Expand Up @@ -267,40 +293,37 @@ export class AppService {
TE.chain(assetIds =>
TE.tryCatch(
() => this.prismaService.$queryRaw`
select
a.asset_id as "assetId",
a.title_public as "titlePublic",
a.create_date as "createDate",
a.asset_kind_item_code as "assetKindItemCode",
a.asset_format_item_code as "assetFormatItemCode",
a.language_item_code as "languageItemCode",
mclr.man_cat_label_item_code as "manCatLabelItemCode",
ac.contact_id as "contactId",
ac.role as "contactRole",
ius.is_available as "internalUse",
pus.is_available as "publicUse",
s.study_id as "studyId",
s.geom_text as "studyGeomText"
from
asset a
inner join
internal_use ius
on ius.internal_use_id = a.internal_use_id
inner join
public_use pus
on pus.public_use_id = a.public_use_id
left join
all_study s
on s.asset_id = a.asset_id
left join
asset_contact ac
on ac.asset_id = a.asset_id
left join
man_cat_label_ref mclr
on ac.asset_id = mclr.asset_id
where
a.asset_id in (${Prisma.join(assetIds)})
`,
select a.asset_id as "assetId",
a.title_public as "titlePublic",
a.create_date as "createDate",
a.asset_kind_item_code as "assetKindItemCode",
a.asset_format_item_code as "assetFormatItemCode",
a.language_item_code as "languageItemCode",
mclr.man_cat_label_item_code as "manCatLabelItemCode",
ac.contact_id as "contactId",
ac.role as "contactRole",
ius.is_available as "internalUse",
pus.is_available as "publicUse",
s.study_id as "studyId",
s.geom_text as "studyGeomText"
from asset a
inner join
internal_use ius
on ius.internal_use_id = a.internal_use_id
inner join
public_use pus
on pus.public_use_id = a.public_use_id
left join
all_study s
on s.asset_id = a.asset_id
left join
asset_contact ac
on ac.asset_id = a.asset_id
left join
man_cat_label_ref mclr
on ac.asset_id = mclr.asset_id
where a.asset_id in (${Prisma.join(assetIds)})
`,
unknownToError,
),
),
Expand Down
58 changes: 28 additions & 30 deletions apps/server-asset-sg/src/app/postgres-studies/postgres-studies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,21 @@ export const PostgresAllStudies = C.array(
geomText: C.string,
}),
);

export interface PostgresAllStudies extends D.TypeOf<typeof PostgresAllStudies> {}

const decodeStudyQueryResult = flow(
export const decodeStudyQueryResult = flow(
PostgresAllStudies.decode,
E.mapLeft(e => new Error(D.draw(e))),
TE.fromEither,
);

const createAllStudyQuery = (whereClause: string) => `
select
asset_id as "assetId",
study_id as "studyId",
geom_text as "geomText"
from
public.all_study
where
${whereClause}
export const createAllStudyQuery = (whereClause: string) => `
select asset_id as "assetId",
study_id as "studyId",
geom_text as "geomText"
from public.all_study
where ${whereClause}
`;

const allStudyQuery = (prismaClient: PrismaClient, whereClause: string): TE.TaskEither<Error, PostgresAllStudies> =>
Expand All @@ -62,15 +60,12 @@ export const postgresStudiesByAssetIds = (
pipe(
TE.tryCatch(
() => prismaClient.$queryRaw`
select
asset_id as "assetId",
study_id as "studyId",
geom_text as "geomText"
from
public.all_study
where
asset_id in (${Prisma.join(assetIds)})
`,
select asset_id as "assetId",
study_id as "studyId",
geom_text as "geomText"
from public.all_study
where asset_id in (${Prisma.join(assetIds)})
`,
unknownToError,
),
TE.chain(decodeStudyQueryResult),
Expand All @@ -94,11 +89,12 @@ export const updateStudies = (prismaClient: PrismaClient, studies: { studyId: st
TE.tryCatch(
() =>
prismaClient.$executeRawUnsafe(
`update public.study_${type} set
geom = st_geomfromtext('${study.geomText}', 2056)
where
study_${type}_id = ${studyId}
and st_equals(geom, st_geomfromtext('${study.geomText}', 2056)) = false`,
`update public.study_${type}
set geom = st_geomfromtext('${study.geomText}', 2056)
where study_${type}_id = ${studyId}
and st_equals(geom
, st_geomfromtext('${study.geomText}'
, 2056)) = false`,
),
unknownToUnknownError,
),
Expand Down Expand Up @@ -132,7 +128,7 @@ export const createStudies = (prismaClient: PrismaClient, assetId: number, study
() =>
prismaClient.$executeRawUnsafe(
`insert into public.study_${type} (asset_id, geom_quality_item_code, geom)
values (${assetId}, 'unkown', st_geomfromtext('${geomText}', 2056))`,
values (${assetId}, 'unkown', st_geomfromtext('${geomText}', 2056))`,
),
unknownToUnknownError,
),
Expand Down Expand Up @@ -170,13 +166,15 @@ export const deleteStudies = (prismaClient: PrismaClient, assetId: number, study
() =>
studyIdsToKeep.length === 0
? prismaClient.$executeRawUnsafe(
`delete from public.study_${type} where asset_id = ${assetId}`,
`delete
from public.study_${type}
where asset_id = ${assetId}`,
)
: prismaClient.$executeRawUnsafe(
`delete from public.study_${type}
where
asset_id = ${assetId}
and study_${type}_id not in (${studyIdsToKeep.join(',')})`,
`delete
from public.study_${type}
where asset_id = ${assetId}
and study_${type}_id not in (${studyIdsToKeep.join(',')})`,
),
unknownToUnknownError,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { postgresStudiesByPolygon } from '../postgres-studies/postgres-studies';

import { makeSearchAssetResult, searchAssetQuery } from './search-asset';

const executeAssetQuery = (prismaClient: PrismaClient, assetIds: number[]) =>
export const executeAssetQuery = (prismaClient: PrismaClient, assetIds: number[]) =>
TE.tryCatch(
() =>
prismaClient.asset.findMany({
Expand All @@ -22,6 +22,7 @@ const executeAssetQuery = (prismaClient: PrismaClient, assetIds: number[]) =>
);

export interface AssetQueryResults extends GetRightTypeOfTaskEither<ReturnType<typeof executeAssetQuery>> {}

export type AssetQueryResult = AssetQueryResults[number];

export function findAssetsByPolygon(prismaClient: PrismaClient, polygon: LV95[]) {
Expand Down

0 comments on commit 5ec7845

Please sign in to comment.