Search code examples
postgresqlgraphqlnestjspostgistypeorm

typeorm geometry type Undefined type error


everyone. I am creating a project that uses geometry data using postgresql postgis this time. So I want to declare geometry in the column and use it, but there's an error. Could you tell me why there is an error?

Multiple official documents were checked, but no method was found. Commenting the coordinate column will create the code normally.

import {
    Column,
    CreateDateColumn,
    Entity,
    JoinColumn,
    ManyToOne,
    PrimaryGeneratedColumn
} from 'typeorm';
import { Location_Group } from './location_group.entity';
import { Geometry } from 'geojson';
import { Field, ID, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
@Entity()
export class Location {
    @Field(() => ID)
    @PrimaryGeneratedColumn('increment')
    id: number;

    @Field(() => String)
    @Column({ type: 'varchar' })
    name: string;

    @Field()
    @Column({
        type: 'geometry',
        nullable: true,
        spatialFeatureType: 'Point',
        srid: 4326
    })
    coordinate: Geometry;

    @Field(() => Int)
    @Column({ type: 'int' })
    order_number: number;

    @Field()
    @CreateDateColumn({ type: 'timestamptz' })
    created_at: Date;

    @Field(() => Location_Group)
    @ManyToOne(
        () => Location_Group,
        (location_group) => location_group.location
    )
    @JoinColumn([{ name: 'location_group_id', referencedColumnName: 'id' }])
    location_group: Location_Group;
}

enter image description here


Solution

  • There is someone who wants me to share the scalar I made, so I write it here. I hope this code helps you.

    import { GraphQLScalarType } from 'graphql';
    
    export const GeoJSONPoint = new GraphQLScalarType({
        name: 'GeoJSONPoint',
        description: 'Geometry scalar type',
        parseValue(value) {
            return value;
        },
    
        serialize(value) {
            return value;
        },
    
        parseLiteral(ast) {
            const geometryData = {
                type: '',
                coordinates: []
            };
    
            for (const i in ast['fields']) {
                if (ast['fields'][i]['name']['value'] == 'type') {
                    if (ast['fields'][i]['value']['value'] != 'point') {
                        return null;
                    }
                    geometryData.type = ast['fields'][i]['value']['value'];
                }
    
                if (ast['fields'][i]['name']['value'] == 'coordinate') {
                    for (const j in ast['fields'][i]['value']['values']) {
                        geometryData.coordinates.push(
                            parseFloat(
                                ast['fields'][i]['value']['values'][j]['value']
                            )
                        );
                    }
                }
            }
            return geometryData;
        }
    });