import { scrape , AdInfo } from "./scraper" ; import { ScraperOptions } from "./helpers" ; function DateToString ( date ) { const m = ( "0" + ( date . getMonth ( ) + 1 ) ) . slice ( - 2 ) ; const d = ( "0" + date . getDate ( ) ) . slice ( - 2 ) ; const y = date . getFullYear ( ) ; const hrs = ( "0" + date . getHours ( ) ) . slice ( - 2 ) ; const mins = ( "0" + date . getMinutes ( ) ) . slice ( - 2 ) ; return `${ m }/${ d }/${ y } @ ${ hrs }:${ mins }` ; } /**
 * This class encapsulates a Kijiji ad and its properties. It also
 * handles retrieving this information from Kijiji
 */ export class Ad extends AdInfo { param url param info param scraped constructor ( url , info = { } , scraped = false ) { super ( ) ; let isScraped = scraped ; const updateInfo = ( info ) : void => { for ( const [ key , value ] of Object . entries ( info ) ) { if ( super . hasOwnProperty ( key ) ) { ( this as any ) [ key ] = value ; } } } ; updateInfo ( info ) ; this . url = url ; this . scrape = ( options ? , callback ? ) : Promise < void > => { const promise = scrape ( this . url , options ) . then ( newInfo => { updateInfo ( newInfo ) ; isScraped = true ; } ) ; if ( callback ) { promise . then ( ( ) => callback ( null ) , callback ) ; } return promise ; } ; this . isScraped = ( ) => isScraped ; } param url param options param callback returns static Get ( url , options ? , callback ? ) { const promise = scrape ( url , options ) . then ( info => { return new Ad ( url , info , true ) ; } ) ; if ( callback ) { promise . then ( ad => callback ( null , ad ) , err => callback ( err , new Ad ( "" ) ) ) ; } return promise ; } returns isScraped : ( ) => boolean ; param options param callback returns scrape : ( options ? : ScraperOptions , callback ? : ( err : Error | null ) => void ) => Promise < void > ; returns toString ( ) { let str = "" ; if ( this . date instanceof Date && ! Number . isNaN ( this . date . getTime ( ) ) ) { str += `[${ DateToString ( this . date ) }] ` ; } if ( this . title ) { str += this . title + "\r\n" ; } str += this . url + "\r\n" ; for ( const attr of Object . keys ( this . attributes ) ) { let val = this . attributes [ attr ] ; if ( attr === "location" && val . mapAddress !== undefined ) val = val . mapAddress ; str += `* ${ attr }: ${ val }\r\n` ; } return str ; } } ;