Ejemplo n.º 1
0
func NewChannelMapper(funcSource string) (*ChannelMapper, error) {
	mapper := &ChannelMapper{}
	var err error
	mapper.js, err = base.NewJSServer(funcSource)
	if err != nil {
		return nil, err
	}

	// Implementation of the 'sync()' callback:
	mapper.js.DefineNativeFunction("sync", func(call otto.FunctionCall) otto.Value {
		for _, arg := range call.ArgumentList {
			if arg.IsString() {
				mapper.channels = append(mapper.channels, arg.String())
			} else if arg.Class() == "Array" {
				array := ottoArrayToStrings(arg.Object())
				if array != nil {
					mapper.channels = append(mapper.channels, array...)
				}
			}
		}
		return otto.UndefinedValue()
	})

	mapper.js.Before = func() {
		mapper.channels = []string{}
	}
	mapper.js.After = func(result otto.Value, err error) (interface{}, error) {
		channels := mapper.channels
		mapper.channels = nil
		return channels, err
	}
	return mapper, nil
}
Ejemplo n.º 2
0
// Creates a new Validator given a CouchDB-style JavaScript validation function.
func NewValidator(funcSource string) (*Validator, error) {
	funcSource = fmt.Sprintf(funcWrapper, funcSource)
	validator := &Validator{}
	var err error
	validator.js, err = base.NewJSServer(funcSource)
	if err != nil {
		return nil, err
	}
	validator.js.After = func(result otto.Value, err error) (interface{}, error) {
		if err != nil {
			return nil, err
		}
		if !result.IsObject() {
			return validatorResult{200, ""}, nil
		}
		resultObj := result.Object()
		statusVal, _ := resultObj.Get("status")
		errMsg, _ := resultObj.Get("msg")
		status, _ := statusVal.ToInteger()
		return validatorResult{int(status), errMsg.String()}, nil
	}
	return validator, nil
}