The Bolg

Back to coding blogs πŸ§πŸΎβ€β™‚οΈ

Was holding off this small addition for no real reason, other than I can’t find an elegant way to parse the info from notion. Basically it comes sequentially, divider β†’ heading1 β†’ image β†’ heading2 β†’ heading3

What i did was a switch case, whenever divider is there i move on to the next iteration.

Dont feel like this is the best way but oh wells. One day I will refactor this

rawBlocks, err := n.cache.GetReadingNowPage(ctx, blockID)
	if err != nil {
		return nil, fmt.Errorf("error getting block children: %v", err)
	}
	// parse rawBlocks into reading book objects
	// then render the reading book objects into html
	// then return the html
	readingNowBlocks := []models.ReadingNowBlock{}
	var currentBook models.ReadingNowBlock
	for i := range rawBlocks {
		var b models.Block
		err := json.Unmarshal(rawBlocks[i], &b)
		if err != nil {
			log.Error("error unmarshalling rawblock: %v", err)
			continue
		}
		switch b.Type {
		case "divider":
			if i != 0 {
				readingNowBlocks = append(readingNowBlocks, currentBook)
			}
			currentBook = models.ReadingNowBlock{}
		case "heading_1":
			// unmarshal into heading1 block
			var heading1Block models.Heading1
			err := json.Unmarshal(rawBlocks[i], &heading1Block)
			if err != nil {
				log.Error("error unmarshalling heading1 block: %v", err)
				continue
			}
			currentBook.Title = heading1Block.Heading1.Text[0].Text.Content
		case "heading_2":
			// unmarshal into heading2 block
			var heading2Block models.Heading2
			err := json.Unmarshal(rawBlocks[i], &heading2Block)
			if err != nil {
				log.Error("error unmarshalling heading2 block: %v", err)
				continue
			}
			currentBook.Author = heading2Block.Heading2.Text[0].Text.Content
		case "heading_3":
			// unmarshal into heading3 block
			var heading3Block models.Heading3
			err := json.Unmarshal(rawBlocks[i], &heading3Block)
			if err != nil {
				log.Error("error unmarshalling heading3 block: %v", err)
				continue
			}
			currentBook.Progress = heading3Block.Heading3.Text[0].Text.Content
		case "image":
			var block models.Image
			err := json.Unmarshal(rawBlocks[i], &block)
			if err != nil {
				log.Error("error unmarshalling image block: %v", err)
				continue
			}
			currentBook.ImageURL = block.Image.File.URL
		}
	}