@function initModelUnlink

link instance to a related model instance

@param {object} args
14583
function initModelUnlink (args) {
    var controller = this
    var model = this.model
    // if model does not have id column then cannot use default controller
    if (!defined(model.columnName('id'))) {
        return
    }
    // set true if model has ny relations that link via another model
    var hasVia = false
    // check for relations
    _.each(model.relations, relation => {
        if (defined(relation.via)) {
            hasVia = true
        }
    })
    // if model does not have via then do not create link endpoing
    if (!hasVia) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = defined(args.defaultRole) 
        ? args.defaultRole
        : defined(accountIdColumn) && model.columns[accountIdColumn].null === false
            ? 'authenticated'
            : 'all'
    // index inputs
    var input = {
        // get current revision of record
        current: ['query.current', 'body.current'],
        // get record even if deleted
        deleted: ['query.deleted', 'body.deleted'],
        // ignore conflicts
        force: ['query.force', 'body.force'],
        // record id
        id: 'params.id',
        // url to redirect to when done
        redirect: ['query.redirect', 'body.redirect'],
        // http referrer
        referrer: 'headers.referer',
        // name of model to link to
        relation: ['query.relation', 'body.relation'],
        // id of model to link to
        relationId: ['query.relationId', 'body.relationId'],
    }
    // create path if it does not exist
    if (!this.paths['/:id/unlink']) {
        this.paths['/:id/unlink'] = {}
    }
    // add handler for POST /:id/link to link record to another
    this.paths['/:id/unlink'].post = this.paths['/:id/unlink'].get = [
        {
            before: function (args) {
                // load primary record and related record
                return loadRecordAndRelation(controller, args)
            },
            input: input,
            method: function (args) {
                // unlink related record from primary record
                return unlinkModel(controller, args)
            },
            methodName: 'unlink',
            role: role,
        },
    ]
}
1313482
function(arg) {
    return /^f/.test(typeof arg) ? /c/.test(document.readyState) ? arg() : u._defInit.push(arg) : new Init(arg);
  }
1209105
function linkModel (controller, args) {
    // get model from controller
    var model = controller.model
    // get record from args
    var record = args[model.name]
    // get relation by name
    var relation = model.relation(args.relation)
    // require relation with via
    if (!relation || !relation.via) {
        httpError(400, 'Invalid Relation')
    }
    // args for create
    var createArgs = {
        session: args.session,
    }
    // set model id
    createArgs[relation.viaModelIdColumn] = record.raw[relation.modelIdColumn]
    createArgs[relation.viaRelationIdColumn] = args.relationId
    // create relation
    return relation.viaModel.createMeta(createArgs)
    // take appropriate action on success
    .then(record => {
        // if json then return raw data
        if (args.json) {
            return record
        }
        // if html then redirect
        else {
            httpRedirect(args.redirect || args.referrer)
        }
    })
}
471956
function (args) {
  if (false === (this instanceof Session)) throw new Error('new operator required');
  args = args || {};
  if (!args.attributes) {
    args.attributes = [];
  }
  var userModelID = new Attribute.ModelID(new User());
  args.attributes.push(new Attribute({name: 'userID', type: 'Model', value: userModelID}));
  args.attributes.push(new Attribute({name: 'dateStarted', type: 'Date', value: new Date()}));
  args.attributes.push(new Attribute({name: 'passCode', type: 'String(20)'}));
  args.attributes.push(new Attribute({name: 'active', type: 'Boolean'}));
  args.attributes.push(new Attribute({name: 'ipAddress', type: 'String'}));

  Model.call(this, args);
  this.modelType = "Session";
  this.set('active', false);
}
63604
function initModelUpdate (args) {
    var controller = this
    var model = this.model
    // if model does not have id column then cannot use default controller
    if (!model.columnName('id') || !model.columnName('parentId')) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // get current revision of instance
        current: 'query.current',
        // get record even if deleted
        deleted: 'query.deleted',
        // ignore conflicts
        force: 'query.force',
        // instance id
        id: 'params.id',
        // merge update data into existing data
        merge: 'query.merge',
        // input data includes meta columns
        meta: 'query.meta',
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path for PUT for API requests
    if (!this.paths['/:id']) {
        this.paths['/:id'] = {}
    }
    // create path for POST for form requests
    if (!this.paths['/:id/update']) {
        this.paths['/:id/update'] = {}
    }
    // add handler for PUT /:id and POST /:id/update
    // to update instance
    this.paths['/:id'].put = this.paths['/:id/update'].post = [
        {
            before: function (args) {
                // load model
                return loadRecordForUpdate(controller, args)
            },

            input: input,
            method: function (args) {
                // perform update
                return update(controller, args)
            },
            methodName: 'update',
            role: role,
            template: 'instance',
        },
    ]
}
505434
function initViews () {
    // list of views - may be empty
    this.modelViews = []
    // if view is false no model views will be applied overriding any defaults
    if (this.args.view === false) {
        return
    }
    // get view from args or default
    var viewArg = defined(this.args.view) ? this.args.view : this.model.views.default
    // skip unless view arg is set from args or default
    if (!defined(viewArg)) {
        return
    }
    // list of views to apply to model
    var views
    // if view is string then convert to array
    if (typeof viewArg === 'string') {
        views = [viewArg]
    }
    // if view is array use it
    else if (Array.isArray(viewArg)) {
        views = viewArg
    }
    // invalid argument
    else {
        throw this.error('invalid view argument')
    }
    // iterate over views getting model view objects
    _.each(views, view => {
        var modelView = requireValidModelView(view, this.model.views, true)
        // if result is array then add all
        if (Array.isArray(modelView)) {
            _.each(modelView, modelView => this.modelViews.push(modelView))
        }
        // otherwise add object
        else {
            this.modelViews.push(modelView)
        }
    })
    // instantiate model view engine if there are views
    if (this.modelViews.length > 0) {
        this.modelViewEngine = new ImmutableCoreModelViewEngine({query: this})
    }
}
353503
function ImmutableCoreController (args) {
    // get copy of original args
    this.args = _.cloneDeep(args)
    // create module and set options
    this.initModule(args)
    // create default paths for model if passed
    this.initModel(args)
    // create paths from arguments
    this.initPaths(args)
    // sort controllers
    this.orderControllers()
}
291750
function linkify(name, fp, append) {
  return mdu.link(name, relative(fp) + (append ? append : ''));
}
678213
function unlink(args, config) {
  const packageName = args[0];

  var project;
  var dependency;

  try {
    project = config.getProjectConfig();
  } catch (err) {
    log.error(
      'ERRPACKAGEJSON',
      'No package found. Are you sure it\'s a React Native project?'
    );
    return Promise.reject(err);
  }

  try {
    dependency = config.getDependencyConfig(packageName);
  } catch (err) {
    log.warn(
      'ERRINVALIDPROJ',
      `Project ${packageName} is not a react-native library`
    );
    return Promise.reject(err);
  }

  const allDependencies = getDependencyConfig(config, getProjectDependencies());
  const otherDependencies = filter(allDependencies, d => d.name !== packageName);
  const thisDependency = find(allDependencies, d => d.name === packageName);
  const iOSDependencies = compact(otherDependencies.map(d => d.config.ios));

  const tasks = [
    () => promisify(thisDependency.config.commands.preunlink || commandStub),
    () => unlinkDependencyAndroid(project.android, dependency, packageName),
    () => unlinkDependencyIOS(project.ios, dependency, packageName, iOSDependencies),
    () => promisify(thisDependency.config.commands.postunlink || commandStub)
  ];

  return promiseWaterfall(tasks)
    .then(() => {
      const assets = difference(
        dependency.assets,
        flatten(allDependencies, d => d.assets)
      );

      if (isEmpty(assets)) {
        return Promise.resolve();
      }

      if (project.ios) {
        log.info('Unlinking assets from ios project');
        unlinkAssetsIOS(assets, project.ios);
      }

      if (project.android) {
        log.info('Unlinking assets from android project');
        unlinkAssetsAndroid(assets, project.android.assetsPath);
      }

      log.info(
        `${packageName} assets has been successfully unlinked from your project`
      );
    })
    .catch(err => {
      log.error(
        `It seems something went wrong while unlinking. Error: ${err.message}`
      );
      throw err;
    });
}
756357
function read (controller, args, links) {
    var record = args[controller.model.name]
    // get local copy of links
    links = _.cloneDeep(links)
    // subsitute any variables in links with values from record
    resolveLinkVariables(links, record)
    // if this is json response return raw data
    if (args.json) {
        return record
    }
    // javascript for page
    var js = []
    // create form to edit instance data
    if (controller.form) {
        var form = controller.form.newInstance({
            action: './'+record.id+'/update',
            mode: 'update',
            record: record,
            submit: {title: 'Update '+changeCase.titleCase(controller.model.name)},
            title: changeCase.titleCase(controller.model.name)+' Record',
        })
        // if form uses ckeditor add js
        if (form.ckeditor) {
            js.push({
                crossorigin: 'anonymous',
                //integrity: 'sha256-TTtB6JD2qVpmE4ydlMyYH52d7OSMq5FQh2f0ECHR0Bw=',
                src: '//cdn.jsdelivr.net/ckeditor/4.3.1/ckeditor.js',
            })
        }
    }
    // related records
    var related = []
    // add related records
    _.each(_.keys(record.related).sort(), relatedName => {
        // get related model
        var relatedModel = controller.model.relation(relatedName).model
        // related records
        var relatedRecords = record.related[relatedName]
        // build actions for related records
        _.each(relatedRecords, relatedRecord => {
            buildActions(relatedModel.controller, relatedRecord, controller, record)
        })
        // get fields for displaying model from controller or build
        var fields = relatedModel.controller && relatedModel.controller.fields || buildFields(relatedModel)
        // add related record with data needed to render
        related.push({
            fields: fields,
            model: relatedModel,
            records: relatedRecords,
        })
    })
    // return form
    return {
        form: form,
        forms: args.forms,
        js: js,
        links: links,
        model: controller.model,
        record: record,
        related: related,
    }
}
770393
function initModelList (args) {
    var controller = this
    var model = this.model
    // make sure args is object
    args = requireValidOptionalObject(args)
    // make sure list is defined
    args.list = requireValidOptionalObject(args.list)
    // make sure query args are object
    var queryArgs = requireValidOptionalObject(args.list.query)
    // create title from name
    var title = model.title+' Records'
    // create new form instance configured to submit from list page
    if (controller.form && _.get(args, 'list.form') !== false) {
        var form = controller.form.newInstance({
            action: './?redirect=./',
        })
    }
    // get role
    var role = args.defaultRole || 'all'
    // build fields for table view
    this.fields = buildFields(model, args.list && args.list.fields)
    // index inputs
    var input = {
        // included deleted records
        deleted: 'query.deleted',
        // limit - overrides value in query if any
        limit: 'query.limit',
        // offset - overrides value in query if any
        offset: 'query.offset',
        // column to sort by
        orderColumn: 'query.orderColumn',
        // direction to sort in
        orderDirection: 'query.orderDirection',
        // free-form search string
        search: 'query.search',
        // list of columns to select
        select: 'query.select',
        // json encoded where arguments
        where: 'query.where',
    }
    // if model has an original id column then add to query options
    if (model.columnName('originalId')) {
        input.originalId = 'query.originalId'
    }
    // add extra columns as query param options
    _.each(model.extraColumns, (spec, name) => {
        // only add column if it has index
        if (!spec.index && !spec.unique) {
            return
        }
        // do not overwrite core inputs
        if (input[name]) {
            return
        }
        // add column to inputs
        input[name] = 'query.'+name
    })
    // links to display at top of page
    var links
    // use links from list view
    if (Array.isArray(args.list.links)) {
        links = args.list.links
    }
    // use global controller links
    else if (Array.isArray(args.links)) {
        links = args.links
    }
    // set default links
    else {
        links = [
            {href: './new', title: 'Create New'},
        ]
    }
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // add list handler for GET on /
    this.paths['/'].get = [
        {
            before: function (args) {
                // load records
                return beforeList(controller, args, _.cloneDeep(controller.fields), title, form, links, queryArgs)
            },
            input: input,
            method: function (args) {
                return args.json
                    ? _.pick(args, ['records', 'result'])
                    : _.pick(args, ['clear', 'fields', 'form', 'links', 'pager', 'query', 'records', 'result', 'title'])
            },
            methodName: 'list',
            role: role,
        },
    ]
}
204529
function ImmutableCoreModelFormInstance (args) {
    // new instance is based on original
    _.merge(this, args.form)
    // deep clone nested data structures
    this.fields = _.cloneDeep(args.form.fields)
    // delete from args so other values can be merged
    delete args.form
    // if record is passed init form values from model instance
    if (args.record) {
        this.initRecord(args.record)
        // delete from args so other values can be merged
        delete args.record
    }
    // if there was input with errors init form with those values
    else if (args.error) {
        this.initInput(args.input, args.error)
        // delete from args so other values can be merged
        delete args.error
        delete args.input
    }
    // if there is only input then init form with pre-fill values
    else if (args.input) {
        this.initInput(args.input)
        // delete from args so other values can be merged
        delete args.input
    }
    // merge remaining args to form
    mergeArgs(this, args)
    // if new instance is in udpate mode and model does not have a parentId
    // column then it cannot be update so disable all fields
    if (args.mode === 'update' && !this.model.columnName('parentId')) {
        // disable all fields
        _.each(this.fields, field => {
            field.readonly = true
        })
        // disable submit
        this.submit = false
    }
}
369663
def link(origin, link_name, force=False, model_path=None):
    
    if util.is_package(origin):
        model_path = util.get_package_path(origin)
    else:
        model_path = Path(origin) if model_path is None else Path(model_path)
    if not model_path.exists():
        prints(Messages.M009.format(path=path2str(model_path)),
               title=Messages.M008, exits=1)
    data_path = util.get_data_path()
    if not data_path or not data_path.exists():
        spacy_loc = Path(__file__).parent.parent
        prints(Messages.M011, spacy_loc, title=Messages.M010, exits=1)
    link_path = util.get_data_path() / link_name
    if link_path.is_symlink() and not force:
        prints(Messages.M013, title=Messages.M012.format(name=link_name),
               exits=1)
    elif link_path.is_symlink():  # does a symlink exist?
        # NB: It's important to check for is_symlink here and not for exists,
        # because invalid/outdated symlinks would return False otherwise.
        link_path.unlink()
    elif link_path.exists(): # does it exist otherwise?
        # NB: Check this last because valid symlinks also "exist".
        prints(Messages.M015, link_path,
               title=Messages.M014.format(name=link_name), exits=1)
    msg = "%s --> %s" % (path2str(model_path), path2str(link_path))
    try:
        symlink_to(link_path, model_path)
    except:
        # This is quite dirty, but just making sure other errors are caught.
        prints(Messages.M017, msg, title=Messages.M016.format(name=link_name))
        raise
    prints(msg, Messages.M019.format(name=link_name), title=Messages.M018)
690635
function (links) {
            var i, len;
            for (i = 0, len = links.length; i < len; ++i) {
                createLink(links[i]);
            }
        }
450957
function update (controller, args) {
    // get model from controller
    var model = controller.model
    // get current instance loaded in before
    var instance = args[model.name+'Orig']
    // get model data from input
    var data = args[model.name]
    //  build update args
    var updateArgs = args.meta ? _.clone(data) : {data: data}
    // set force flag based on input
    if (args.force) {
        updateArgs.force = true
    }
    // set the merge flag to false unless explicitly set true
    if (!args.merge) {
        updateArgs.merge = false
    }
    // do update
    return instance.updateMeta(updateArgs)
    // redirect on success
    .then(instance => {
        // if in json mode return instance data
        if (args.json) {
            return instance
        }
        // otherwise redirect to instance page
        else {
            // use redirect from input or redirect to new instance
            var url = args.redirect || '../'+instance.id
            // redirect
            httpRedirect(url)
        }
    })
    // catch errors
    .catch(error => {
        // if error is redirect throw it
        if (error.code === 302) {
            throw error
        }
        // for version conflict errors return the current instance with the
        // error data and throw a 409 http error
        if (instance.isConflictError(error)) {
            // get current instance
            return instance.current()
            // throw 409 conflic error with current instance data
            .then(current => {
                // if in json mode return error with data
                if (args.json) {
                    httpError(409, undefined, current)
                }
                // otherwise redirect to current instance
                else {
                    httpRedirect('../'+current.id+'?error=conflict')
                }
            })
        }
        // if in json mode or there is no form return 400 error
        if (args.json || !controller.form) {
            httpError(400, undefined, _.pick(error, ['data', 'message']))
        }
        // create new form instance with input and error data
        var form = controller.form.newInstance({
            action: './update',
            input: data,
            error: error,
        })
        // javascript for page
        var js = []
        // if form uses ckeditor add js
        if (form.ckeditor) {
            js.push({
                crossorigin: 'anonymous',
                //integrity: 'sha256-TTtB6JD2qVpmE4ydlMyYH52d7OSMq5FQh2f0ECHR0Bw=',
                src: '//cdn.jsdelivr.net/ckeditor/4.3.1/ckeditor.js',
            })
        }
        // return form
        return {
            form: form,
            js: js,
        }
    })
}
992924
function ImmutableCoreModelQuery (args) {
    // require model
    this.assert(defined(args.model) && args.model.ImmutableCoreModel, 'model required')
    // set model for query
    this.model = args.model
    // args and session are both optional in some cases
    this.args = _.cloneDeep( requireValidOptionalObject(args.args) )
    this.session = requireValidOptionalObject(args.session)
    // validate and normalize args
    this.initArgs()
    // valid view args and instantiate model view engine if there are views
    this.initViews()
}
358085
function initModelNew (args) {
    var controller = this
    var model = this.model
    // if model/controller does not have form then cannot create new controller
    if (!this.form) {
        return
    }
    // create path if it does not exist
    if (!this.paths['/new']) {
        this.paths['/new'] = {}
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // form inputs
    var input = {
        redirect: 'query.redirect',
    }
    // input may include pre-filled form values
    input[model.name] = 'query.'+model.name
    // add handler for GET /new
    this.paths['/new'].get = [
        {
            before: function (args) {
                return newInstance(controller, args)
            },
            input: input,
            method: function (args) {
                return {form: args.form}
            },
            methodName: 'new',
            role: role,
            template: 'instance',
        },
    ]
}