1// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package unified
8
9import (
10	"fmt"
11
12	"go.mongodb.org/mongo-driver/bson"
13	"go.mongodb.org/mongo-driver/mongo/options"
14)
15
16type DBOrCollectionOptions struct {
17	DBOptions         *options.DatabaseOptions
18	CollectionOptions *options.CollectionOptions
19}
20
21// UnmarshalBSON specifies custom BSON unmarshalling behavior to convert db/collection options from BSON/JSON documents
22// to their corresponding Go objects.
23func (d *DBOrCollectionOptions) UnmarshalBSON(data []byte) error {
24	var temp struct {
25		RC    *readConcern           `bson:"readConcern"`
26		RP    *readPreference        `bson:"readPreference"`
27		WC    *writeConcern          `bson:"writeConcern"`
28		Extra map[string]interface{} `bson:",inline"`
29	}
30	if err := bson.Unmarshal(data, &temp); err != nil {
31		return fmt.Errorf("error unmarshalling to temporary DBOrCollectionOptions object: %v", err)
32	}
33	if len(temp.Extra) > 0 {
34		return fmt.Errorf("unrecognized fields for DBOrCollectionOptions: %v", MapKeys(temp.Extra))
35	}
36
37	d.DBOptions = options.Database()
38	d.CollectionOptions = options.Collection()
39	if temp.RC != nil {
40		rc := temp.RC.toReadConcernOption()
41		d.DBOptions.SetReadConcern(rc)
42		d.CollectionOptions.SetReadConcern(rc)
43	}
44	if temp.RP != nil {
45		rp, err := temp.RP.toReadPrefOption()
46		if err != nil {
47			return fmt.Errorf("error parsing read preference document: %v", err)
48		}
49
50		d.DBOptions.SetReadPreference(rp)
51		d.CollectionOptions.SetReadPreference(rp)
52	}
53	if temp.WC != nil {
54		wc, err := temp.WC.toWriteConcernOption()
55		if err != nil {
56			return fmt.Errorf("error parsing write concern document: %v", err)
57		}
58
59		d.DBOptions.SetWriteConcern(wc)
60		d.CollectionOptions.SetWriteConcern(wc)
61	}
62
63	return nil
64}
65