mirror of
https://github.com/discourse/discourse.git
synced 2025-04-10 23:50:48 +08:00
FIX: Use first supported type item when JSON-LD returns array (#17217)
This commit is contained in:
parent
20e34b5da6
commit
3baefa25b5
@ -4,6 +4,7 @@ module Onebox
|
|||||||
class JsonLd < Normalizer
|
class JsonLd < Normalizer
|
||||||
# Full schema.org hierarchy can be found here: https://schema.org/docs/full.html
|
# Full schema.org hierarchy can be found here: https://schema.org/docs/full.html
|
||||||
MOVIE_JSON_LD_TYPE = "Movie"
|
MOVIE_JSON_LD_TYPE = "Movie"
|
||||||
|
SUPPORTED_TYPES = [MOVIE_JSON_LD_TYPE]
|
||||||
|
|
||||||
def initialize(doc)
|
def initialize(doc)
|
||||||
@data = extract(doc)
|
@data = extract(doc)
|
||||||
@ -17,6 +18,11 @@ module Onebox
|
|||||||
doc.css('script[type="application/ld+json"]').each do |element|
|
doc.css('script[type="application/ld+json"]').each do |element|
|
||||||
parsed_json = parse_json(element.text)
|
parsed_json = parse_json(element.text)
|
||||||
|
|
||||||
|
if parsed_json.kind_of?(Array)
|
||||||
|
parsed_json = parsed_json.detect { |x| SUPPORTED_TYPES.include?(x["@type"]) }
|
||||||
|
return {} if !parsed_json
|
||||||
|
end
|
||||||
|
|
||||||
case parsed_json["@type"]
|
case parsed_json["@type"]
|
||||||
when MOVIE_JSON_LD_TYPE
|
when MOVIE_JSON_LD_TYPE
|
||||||
return Onebox::Movie.new(parsed_json).to_h
|
return Onebox::Movie.new(parsed_json).to_h
|
||||||
|
@ -47,6 +47,27 @@ describe Onebox::JsonLd do
|
|||||||
expect(json_ld.data).to eq(expected_movie_hash)
|
expect(json_ld.data).to eq(expected_movie_hash)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'returns first supported type when JSON-LD is an array' do
|
||||||
|
array_json = '<script type="application/ld+json">[{"@type": "Something Else"}, {"@context":"https://schema.org","@type":"Movie","url":"/title/tt2358891/","name":"La grande bellezza","alternateName":"The Great Beauty"}]</script>'
|
||||||
|
doc = Nokogiri::HTML(array_json)
|
||||||
|
json_ld = described_class.new(doc)
|
||||||
|
expect(json_ld.data).to eq({
|
||||||
|
description: nil,
|
||||||
|
duration: nil,
|
||||||
|
genres: nil,
|
||||||
|
image: nil,
|
||||||
|
name: "La grande bellezza",
|
||||||
|
rating: nil
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not fail when JSON-LD returns an array with no supported types' do
|
||||||
|
array_json = '<script type="application/ld+json">[{"@type": "Something Else"}, {"@context":"https://schema.org","@type":"Nothing"},{"@context":"https://schema.org"}]</script>'
|
||||||
|
doc = Nokogiri::HTML(array_json)
|
||||||
|
json_ld = described_class.new(doc)
|
||||||
|
expect(json_ld.data).to eq({})
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def expected_movie_hash
|
def expected_movie_hash
|
||||||
|
Loading…
x
Reference in New Issue
Block a user