Example #1
0
// NewModelWithPath allocates and returns a new Model,
// using the given path as it's json file path
func NewModelWithPath(path string, router *Router) (*Model, error) {
	// open file
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	model := NewModel(router)
	bytes := []byte{}

	err = gtester.NewInspector().
		Check(func() error { bytes, err = ioutil.ReadAll(file); return err }).
		Check(func() error { return json.Unmarshal(bytes, model) }).
		Check(model.CheckRelationshipsMeta).
		Check(model.CheckColumnsMeta).
		Check(model.ValidateSeedsValue).
		Then(func() {
			model.initSet()
		})

	return model, err
}
Example #2
0
// NewWithApiDir alloactes and returns a new ApiFaker with the given dir as its ApiDir,
// the error will not be nil if
//   1. dir is wrong
//   2. json file format is wrong
//   3. break rules described in README.md
func NewWithApiDir(dir string) (*ApiFaker, error) {
	faker := &ApiFaker{
		ApiDir:  dir,
		Routers: map[string]*Router{},
	}

	err := gtester.NewInspector().Check(func() error {
		return filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
			if f == nil {
				return err
			}
			if f.IsDir() || !strings.HasSuffix(path, ".json") {
				return nil
			}

			if router, err := NewRouterWithPath(path, faker); err != nil {
				return err
			} else {
				if _, ok := faker.Routers[router.Model.Name]; ok {
					return JsonFileErrorf("%s has been existed", router.Model.Name)
				} else {
					faker.Routers[router.Model.Name] = router
				}
			}
			return nil
		})
	}).
		Check(faker.CheckUniqueness).
		Check(faker.CheckRelationships).
		Then(func() {
			faker.setHandlers()
			faker.setSaveToFileTimer()
		})

	return faker, err
}